package com.ztgf.commodity.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.google.common.base.Joiner;
import com.ztgf.commodity.common.config.YmlConfig;
import com.ztgf.commodity.mapper.BrandInfoMapper;
import com.ztgf.commodity.mapper.CommodityDetailsPageMapper;
import com.ztgf.commodity.mapper.CommodityInfoMapper;
import com.ztgf.commodity.models.bo.*;
import com.ztgf.commodity.models.dto.*;
import com.ztgf.commodity.models.service.*;
import com.ztgf.commodity.models.vo.*;
import com.ztgf.common.constant.CommonParameter;
import com.ztgf.common.constant.Result;
import com.ztgf.common.enums.CodeEnum;
import com.ztgf.common.utils.*;
import com.ztgf.db.utils.RedisUtil;
import com.ztgf.message.model.bo.MessageAnnouncementSaveBO;
import com.ztgf.message.model.constant.MessageTopicType;
import com.ztgf.message.model.dto.ResponseDTO;
import com.ztgf.message.model.enums.MessageEnum;
import com.ztgf.message.model.service.IKafkaProducerService;
import com.ztgf.search.models.dto.EsGoodsDTO;
import com.ztgf.search.models.dto.EsShopDTO;
import com.ztgf.search.models.service.ElasticsearchService;
import com.ztgf.search.models.service.IShopSearchService;
import com.ztgf.search.models.service.SearchService;
import com.ztgf.shopping.models.dto.shop.ShopCategoryRelationDTO;
import com.ztgf.shopping.models.dto.shop.ShopInfoDTO;
import com.ztgf.shopping.models.dto.shop.ShopQualificationDTO;
import com.ztgf.shopping.models.enums.ShoppingCodeEnum;
import com.ztgf.shopping.models.service.epg.IEpgShopSectionService;
import com.ztgf.shopping.models.service.shop.IShopCategoryRelationService;
import com.ztgf.shopping.models.service.shop.IShopInfoService;
import com.ztgf.shopping.models.service.shop.IShopQualificationService;
import com.ztgf.sys.models.dto.SysAreaDTO;
import com.ztgf.sys.models.dto.SysUserDTO;
import com.ztgf.user.models.dto.UserInfoDTO;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.scheduling.annotation.Async;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.*;

import static com.ztgf.common.utils.UtilConstants.*;

/**
 * author: chenyu.wang
 * date: 2020-05-25 14:51
 * Description:
 */
@Slf4j
@DubboService
public class
CommodityInfoServiceImpl extends ServiceImpl<CommodityInfoMapper, CommodityInfoDTO> implements ICommodityInfoService {

    @Resource
    private YmlConfig ymlConfig;
    @DubboReference
    private ICommodityAuditLogService auditLogService;
    @DubboReference
    private ICommoditySpecificationRelationService commoditySpecificationRelationService;
    @DubboReference
    private ICommoditySpecificationService commoditySpecificationService;
    @DubboReference
    private ICommodityComboRelationService commodityComboRelationService;
    @DubboReference
    private ICommodityParamValueRelationService commodityParamValueRelationService;
    @DubboReference
    private IEpgShopSectionService iEpgShopSectionService;
    @Autowired
    private CommodityDetailsPageMapper commodityDetailsPageMapper;
    @Autowired
    private RedisUtil redisUtil;
    @DubboReference
    private IShopQualificationService shopQualificationService;
    @DubboReference
    private ICommodityFilterAttributesService commodityFilterAttributesService;
    @DubboReference
    private ICommodityCategoryService commodityCategoryService;
    @DubboReference
    private IShopInfoService shopInfoService;
    @DubboReference
    private ICommodityParamService commodityParamService;
    @DubboReference
    private IKafkaProducerService iKafkaProducerService;
    @DubboReference
    private ICommoditySalesAttributesRelationService commoditySalesAttributesRelationService;
    @DubboReference
    private SearchService searchService;
    @DubboReference
    private ICommodityLabelService commodityLabelService;
    @Autowired
    private BrandInfoMapper brandInfoMapper;
    @DubboReference
    private ElasticsearchService elasticsearchService;
    @DubboReference
    private IShopCategoryRelationService shopCategoryRelationService;
    @DubboReference
    private IShopInfoService iShopInfoService;
    @DubboReference
    private IShopSearchService shopSearchService;

    /**
     * 根据店铺id获取热销
     *
     * @param shopId 卖家店铺id
     * @return
     */
    @Override
    public List<CommodityInfoHotSellVO> getShopHotSell(Long shopId) {
        List<CommodityInfoHotSellVO> list = baseMapper.getHotSellListById(shopId);
        if(CustomizeUtil.listIsNotNull(list)){
            list.removeIf(commodityInfoHotSellVO -> null != commodityInfoHotSellVO.getIsPublish() && commodityInfoHotSellVO.getIsPublish() == 0);
        }
        return list;
    }

    /**
     * @Description: 根据品牌id查询商品, 批量下架商品
     * @Author: WangChenYu
     * @Param: [id:品牌id]
     * @Date: 2020-10-09 15:04
     */
    @Async
    @Override
    public void updateBatchPublish(Long id) {
        List<CommodityInfoDTO> list = new ArrayList<>();
        Wrapper<CommodityInfoDTO> wrapper = new EntityWrapper<>();
        wrapper.eq("brand_id", id).or().eq("category_id", id).or().eq("shop_id", id);
        List<CommodityInfoDTO> goodsList = this.selectList(wrapper);
        if (goodsList != null && goodsList.size() > 0) {
            for (CommodityInfoDTO infoDTO : goodsList) {
                infoDTO.setIsPublish(ZERO);
                list.add(infoDTO);
            }
            this.updateBatchById(list);
        }
    }

    /**
     * @Description: 逻辑删除/恢复
     * @Author: WangChenYu
     * @Param: [id]
     * @Date: 2020-10-09 15:05
     */
    @Override
    public Result<List<String>> deleteLogic(Long id) {
        Result<List<String>> result = new Result<>();
        CommodityInfoDTO dto = this.selectById(id);
        if (dto == null) {
            result.setCode(CodeEnum.FAIL_100009.getCode());
            result.setMsg(CodeEnum.FAIL_100009.getMsg());
            return result;
        }
        //判断店铺是否冻结
        boolean checkShopIsClose = shopInfoService.checkShopIsClose(dto.getShopId());
        if (!checkShopIsClose) {
            result.setCode(CodeEnum.FAIL_COMMODITY_ERROR_340015.getCode());
            result.setMsg(CodeEnum.FAIL_COMMODITY_ERROR_340015.getMsg());
            return result;
        }
        if (dto.getIsPublish() == ONE) {
            result.setCode(CodeEnum.FAIL_COMMODITY_ERROR_340007.getCode());
            result.setMsg(CodeEnum.FAIL_COMMODITY_ERROR_340007.getMsg());
            return result;
        }
        if (dto.getStatus().equals(ZERO)) {
            //删除
            CommodityInfoDTO deleteDto = new CommodityInfoDTO();
            deleteDto.setId(dto.getId());
            deleteDto.setStatus(ONE);
            boolean update = this.updateById(deleteDto);
            if (!update) {
                result.setCode(CodeEnum.FAIL_100009.getCode());
                result.setMsg(CodeEnum.FAIL_100009.getMsg());
                return result;
            }

            //从es中删除商品
            //searchService.deleteData("index_goods_2020", "goods", dto.getId().toString());
        } else {
            //判断是否由平台删除
            if (dto.getIsPlatformRemove() == ONE) {
                result.setCode(CodeEnum.FAIL_COMMODITY_ERROR_340016.getCode());
                result.setMsg(CodeEnum.FAIL_COMMODITY_ERROR_340016.getMsg());
                return result;
            }
            //恢复
            CommodityInfoDTO deleteDto = new CommodityInfoDTO();
            deleteDto.setId(dto.getId());
            deleteDto.setStatus(ZERO);
            boolean update = this.updateById(deleteDto);
            if (!update) {
                result.setCode(CodeEnum.FAIL_100009.getCode());
                result.setMsg(CodeEnum.FAIL_100009.getMsg());
                return result;
            }

            // 恢复数据后将商品添加进ES
//            CommodityEsVO goods = baseMapper.queryESGoodsById(dto.getId());
//            List<EsGoodsDTO> esGoods = this.getEsGoods(goods);
//            searchService.addGoods("index_goods_2020", "goods", 0, esGoods.size(), esGoods);

        }
        List<EsShopDTO> esShop = iShopInfoService.queryEsShop(dto.getShopId().toString());
        shopSearchService.updateShop(dto.getShopId().toString(), "index_shop_2020", "", 0, esShop.size(), esShop);
        result.setCode(CodeEnum.SUCCESS.getCode());
        result.setMsg(CodeEnum.SUCCESS.getMsg());
        return result;
    }

    /**
     * @Description: 商品上架/下架
     * @Author: WangChenYu
     * @Param: [id]
     * @Date: 2020-10-09 15:07
     */
    @Override
    public Result<List<String>> updateStatus(Long id) {
        CommodityInfoDTO dto = this.selectById(id);
        Result<List<String>> result = new Result<>();
        if (dto == null) {
            result.setCode(CodeEnum.FAIL_COMMODITY_ERROR_340000.getCode());
            result.setMsg(CodeEnum.FAIL_COMMODITY_ERROR_340000.getMsg());
            return result;
        }
        //判断店铺是否冻结
        boolean checkShopIsClose = shopInfoService.checkShopIsClose(dto.getShopId());
        if (!checkShopIsClose) {
            result.setCode(CodeEnum.FAIL_COMMODITY_ERROR_340015.getCode());
            result.setMsg(CodeEnum.FAIL_COMMODITY_ERROR_340015.getMsg());
            return result;
        }
        //审核未通过的商品不能上下架
        if (dto.getAuditStatus() != ONE) {
            result.setCode(CodeEnum.FAIL_COMMODITY_ERROR_340001.getCode());
            result.setMsg(CodeEnum.FAIL_COMMODITY_ERROR_340001.getMsg());
            return result;
        }
        //判断是否由平台下架，平台下架之后不能上架
        if (dto.getIsPlatformShelf() == ONE) {
            result.setCode(CodeEnum.FAIL_COMMODITY_ERROR_340002.getCode());
            result.setMsg(CodeEnum.FAIL_COMMODITY_ERROR_340002.getMsg());
            return result;
        }
        boolean expireStatus = shopQualificationService.getExpireStatus(dto.getShopId(), dto.getBrandId());
        if (!expireStatus) {
            result.setCode(CodeEnum.FAIL_COMMODITY_ERROR_340013.getCode());
            result.setMsg(CodeEnum.FAIL_COMMODITY_ERROR_340013.getMsg());
            return result;
        }
        if (dto.getIsPublish() == ZERO) {
            CommodityInfoDTO updateDto = new CommodityInfoDTO();
            updateDto.setId(dto.getId());
            updateDto.setIsPublish(ONE);//上架
            boolean update = this.updateById(updateDto);
            if (!update) {
                result.setCode(CodeEnum.FAIL_COMMODITY_ERROR_340003.getCode());
                result.setMsg(CodeEnum.FAIL_COMMODITY_ERROR_340003.getMsg());
                return result;
            }
            List<Long> ids = new ArrayList<>();
            ids.add(dto.getId());
            //判断商品是否掌柜推荐 0否、1是
            if (dto.getIsRecommend() == ONE) {
                iEpgShopSectionService.addShopSectionBySectionType(ids, dto.getShopId(),
                        ShoppingCodeEnum.SHOPPER_RECOMMEND_3.getMsg());
            }
            // 是否新品上架 0否、1是
            if (dto.getIsNew() == ONE) {
                iEpgShopSectionService.addShopSectionBySectionType(ids, dto.getShopId(),
                        ShoppingCodeEnum.NEW_SHOP_1.getMsg());
            }
            // 是否镇店之宝 0否、1是
            if (dto.getIsTreasure() == ONE) {
                iEpgShopSectionService.addShopSectionBySectionType(ids, dto.getShopId(),
                        ShoppingCodeEnum.SHOP_BABY_2.getMsg());
            }
            // 将商品添加进ES
            CommodityEsVO goods = baseMapper.queryESGoodsById(dto.getId());
            List<EsGoodsDTO> esGoods = this.getEsGoods(goods);
            searchService.addGoods("index_goods_2020", "goods", 0, esGoods.size(), esGoods);
            result.setCode(CodeEnum.SUCCESS.getCode());
            result.setMsg(CodeEnum.SUCCESS.getMsg());
            return result;
        } else {
            CommodityInfoDTO updateDto = new CommodityInfoDTO();
            updateDto.setId(dto.getId());
            updateDto.setIsPublish(ZERO);//下架
            boolean update = this.updateById(updateDto);
            if (!update) {
                result.setCode(CodeEnum.FAIL_COMMODITY_ERROR_340004.getCode());
                result.setMsg(CodeEnum.FAIL_COMMODITY_ERROR_340004.getMsg());
                return result;
            }
            List<Long> ids = new ArrayList<>();
            ids.add(dto.getId());
            //判断商品是否掌柜推荐 0否、1是
            if (dto.getIsRecommend() == ONE) {
                iEpgShopSectionService.deleteShopSectionBySectionType(ids, dto.getShopId(),
                        ShoppingCodeEnum.SHOPPER_RECOMMEND_3.getMsg());
            }
            // 是否新品上架 0否、1是
            if (dto.getIsNew() == ONE) {
                iEpgShopSectionService.deleteShopSectionBySectionType(ids, dto.getShopId(),
                        ShoppingCodeEnum.NEW_SHOP_1.getMsg());
            }
            // 是否镇店之宝 0否、1是
            if (dto.getIsTreasure() == ONE) {
                iEpgShopSectionService.deleteShopSectionBySectionType(ids, dto.getShopId(),
                        ShoppingCodeEnum.SHOP_BABY_2.getMsg());
            }
            //从es中删除商品
            searchService.deleteData("index_goods_2020", "goods", dto.getId().toString());
            result.setCode(CodeEnum.SUCCESS.getCode());
            result.setMsg(CodeEnum.SUCCESS.getMsg());
            return result;
        }
    }

    /**
     * @Description: 保存发布商品
     * @Author: WangChenYu
     * @Param: [bo]
     * @Date: 2020-10-09 15:10
     */
    @Transactional
    @Override
    public Result<List<String>> saveReleaseCommodity(CommodityReleaseBO bo) {
        Result<List<String>> result = new Result<>();
        //判断店铺是否冻结
        boolean checkShopIsClose = shopInfoService.checkShopIsClose(bo.getShopId());
        if (!checkShopIsClose) {
            result.setCode(CodeEnum.FAIL_COMMODITY_ERROR_340015.getCode());
            result.setMsg(CodeEnum.FAIL_COMMODITY_ERROR_340015.getMsg());
            return result;
        }
        //检查店铺资质是否过期
        Wrapper<ShopQualificationDTO> wrapper = new EntityWrapper<>();
        wrapper.eq("shop_id",bo.getShopId());
        List<ShopQualificationDTO> shopQualificationDTOS = shopQualificationService.selectList(wrapper);
        if (CustomizeUtil.listIsNotNull(shopQualificationDTOS)){
            for (ShopQualificationDTO dto : shopQualificationDTOS) {
                if (dto.getExpireStatus()==2) {
                    if (dto.getType() <= 2) {
                        result.setCode(CodeEnum.FAIL_SHOP_BASIC_CERTIFICATION_EXPIRE_3011.getCode());
                        result.setMsg(CodeEnum.FAIL_SHOP_BASIC_CERTIFICATION_EXPIRE_3011.getMsg());
                        return result;
                    } else {
                        if (bo.getBrandId().equals(dto.getBrandId())){
                            if (dto.getType()==3){
                                for (ShopQualificationDTO shopQualificationDTO : shopQualificationDTOS) {
                                    if (shopQualificationDTO.getType()==4 && shopQualificationDTO.getExpireStatus()==2){
                                        result.setCode(CodeEnum.FAIL_COMMODITY_ERROR_340013.getCode());
                                        result.setMsg(CodeEnum.FAIL_COMMODITY_ERROR_340013.getMsg());
                                        return result;
                                    }
                                }
                            }else {
                                result.setCode(CodeEnum.FAIL_COMMODITY_ERROR_340013.getCode());
                                result.setMsg(CodeEnum.FAIL_COMMODITY_ERROR_340013.getMsg());
                                return result;
                            }
                        }
                    }
                }
            }
        }
        CommodityInfoDTO commodityInfoDTO = new CommodityInfoDTO();
        commodityInfoDTO.setId(ymlConfig.getPkId());
        List<String> stringList = new ArrayList<>();
        stringList.add (commodityInfoDTO.getId ().toString ());
        result.setData (stringList);

        //处理京东商品直接审核通过并发布
        if(bo.getJdFlag().intValue() == 1){
            commodityInfoDTO.setAuditStatus(bo.getAuditStatus());
            commodityInfoDTO.setIsPublish(bo.getIsPublish());
            commodityInfoDTO.setJdFlag(bo.getJdFlag());
        }

        if (StringUtils.isNotBlank(bo.getLogoUrl())) {
            commodityInfoDTO.setLogoUrl(bo.getLogoUrl());
        }
        if (StringUtils.isNotBlank(bo.getLogoUrls())) {
            commodityInfoDTO.setLogoUrls(bo.getLogoUrls());
        }
        if (StringUtils.isNotBlank(bo.getVideoUrls())) {
            commodityInfoDTO.setVideoUrls(bo.getVideoUrls());
        }
        if (StringUtils.isNotBlank(bo.getName())) {
            commodityInfoDTO.setName(bo.getName());
        }
        if (StringUtils.isNotBlank(bo.getDescription())) {
            commodityInfoDTO.setDescription(bo.getDescription());
        }
        if (StringUtils.isNotBlank(bo.getJdPageNum())) {
            commodityInfoDTO.setJdPageNum(bo.getJdPageNum());
        }
        if (null != bo.getSendAreaId()) {
            commodityInfoDTO.setSendAreaId(bo.getSendAreaId());
        }
        if (StringUtils.isNotBlank(bo.getAvailableArea())) {
            commodityInfoDTO.setAvailableArea(bo.getAvailableArea());
        }
        if (null != bo.getSendDays()) {
            commodityInfoDTO.setSendDays(bo.getSendDays());
        }
        if (null != bo.getType()) {
            commodityInfoDTO.setType(bo.getType());
            if (bo.getType() != 1) {
                commodityInfoDTO.setPayType(ZERO);//全额
            } else {
                commodityInfoDTO.setPayType(ONE);//分期
            }
        }
        if (null != bo.getShopId()) {
            commodityInfoDTO.setShopId(bo.getShopId());
        }
        if (null != bo.getBrandId()) {
            commodityInfoDTO.setBrandId(bo.getBrandId());
        }
        if (null != bo.getCategoryId()) {
            commodityInfoDTO.setCategoryId(bo.getCategoryId());
        }
        if (StringUtils.isNotBlank(bo.getNotes())) {
            commodityInfoDTO.setNotes(bo.getNotes());
        }
        if (null != bo.getIsRecommend()) {
            commodityInfoDTO.setIsRecommend(bo.getIsRecommend());
        }
        if (null != bo.getIsNew()) {
            commodityInfoDTO.setIsNew(bo.getIsNew());
        }
        if (null != bo.getIsTreasure()) {
            commodityInfoDTO.setIsTreasure(bo.getIsTreasure());
        }
        if (null != bo.getWarrantyMonth()) {
            commodityInfoDTO.setWarrantyMonth(bo.getWarrantyMonth());
        }
        if (StringUtils.isNotBlank(bo.getProductSpecificationUrl())) {
            commodityInfoDTO.setProductSpecificationUrl(bo.getProductSpecificationUrl());
        }
        if(StringUtils.isEmpty(bo.getCommodityNumber())){
            commodityInfoDTO.setCommodityNumber(OrderNumberUtils.getOrderNumber());
        }else{
            commodityInfoDTO.setCommodityNumber(bo.getCommodityNumber());
        }

        if (StringUtils.isNotBlank(bo.getProductCertificateUrls())) {
            commodityInfoDTO.setProductCertificateUrls(bo.getProductCertificateUrls());
        }
        if (null != bo.getIsVipDiscounts()) {
            commodityInfoDTO.setIsVipDiscounts(bo.getIsVipDiscounts());
        }
        if (null != bo.getFirstBalance()) {
            commodityInfoDTO.setFirstBalance(bo.getFirstBalance());
        }
        if (null != bo.getTailBalance()) {
            commodityInfoDTO.setTailBalance(bo.getTailBalance());
        }
        if (null != bo.getSellerAddressId()) {
            commodityInfoDTO.setSellerAddressId(bo.getSellerAddressId());
        }
        if (null != bo.getIsInquiry()) {
            commodityInfoDTO.setIsInquiry(bo.getIsInquiry());
        }
        if (StringUtils.isNotBlank(bo.getFilterIds())) {
            commodityInfoDTO.setFilterIds(bo.getFilterIds());
        }
        if (StringUtils.isNotBlank(bo.getLabelIds())) {
            commodityInfoDTO.setLabelIds(getIds(bo.getLabelIds()));
        }
        if (bo.getStockDays() != null) {
            commodityInfoDTO.setStockDays(bo.getStockDays());
        }
        //保存商品基本信息
        boolean insert = this.insert(commodityInfoDTO);
        if (!insert) {
            result.setCode(CodeEnum.FAIL_COMMODITY_ERROR_340005.getCode());
            result.setMsg(CodeEnum.FAIL_COMMODITY_ERROR_340005.getMsg());
            return result;
        }
        //保存商品规格信息
        if (StringUtils.isNotBlank(bo.getAttrs())) {
            this.saveGoodsAttrs(bo.getAttrs(), commodityInfoDTO.getId());
        }
        //商品套餐信息
        if (StringUtils.isNotBlank(bo.getCombos())) {
            this.saveGoodsCombo(bo.getCombos(), commodityInfoDTO.getId());
        }
        //商品参数信息
        if (StringUtils.isNotBlank(bo.getParamValues())) {
            this.saveParamValue(bo.getParamValues(), commodityInfoDTO.getId());
        }
        // 销售属性
        if (StringUtils.isNotBlank(bo.getSalesAttributes())) {
            this.saveSalesAttributes(bo.getSalesAttributes(), commodityInfoDTO.getId());
        }
        //保存审核日志
        CommodityAuditLogSaveBO logSaveBO = new CommodityAuditLogSaveBO();
        ShopInfoDTO shopInfoDTO = shopInfoService.selectById (bo.getShopId ());
        if (shopInfoDTO != null){
            logSaveBO.setAdminId(shopInfoDTO.getUserId ());
        }
        logSaveBO.setShopId(bo.getShopId());//卖家店铺id
        logSaveBO.setAuditStatus(0);//审核状态
        logSaveBO.setCommodityId(commodityInfoDTO.getId());//商品id
//        String params = JSON.toJSONString (bo);
//        log.info ("bo--JSON---2" + params);
//        logSaveBO.setParams (params);
        auditLogService.add(logSaveBO);
        // 发送消息
        this.sendMsg(0L, "商品审核", "有新的商品需要审核!", 0L, 3);

        //如果京东商品，上架发布并直接更新ES
//        if(bo.getJdFlag().intValue() == 1){
//            CommodityEsVO goods = baseMapper.queryESGoodsById(commodityInfoDTO.getId());
//            List<EsGoodsDTO> esGoods = this.getEsGoods(goods);
//            searchService.addGoods("index_goods_2020", "goods", 0, esGoods.size(), esGoods);
//        }
        result.setCode(CodeEnum.SUCCESS.getCode());
        result.setMsg(CodeEnum.SUCCESS.getMsg());
        return result;
    }


    /**
     * @Description: 获取商品集合
     * @Author: WangChenYu
     * @Param: [bo]
     * @Date: 2020-10-09 15:10
     */
    @Override
    public Map<String,List> getCommodityList(List<CommodityReleaseBO> commodityReleaseBOList) {
        Map<String,List> commdityReleaseMap = new HashMap<>();
        List<CommodityInfoDTO> commodityInfoDTOList = new ArrayList<>();
        List<CommodityComboRelationDTO> commodityComboRelationDTOList = new ArrayList<>();

        for(CommodityReleaseBO bo : commodityReleaseBOList){
            CommodityInfoDTO commodityInfoDTO = new CommodityInfoDTO();
            commodityInfoDTO.setId(ymlConfig.getPkId());
            //判断店铺是否冻结
            boolean checkShopIsClose = shopInfoService.checkShopIsClose(bo.getShopId());
            if (!checkShopIsClose) {
                continue;
            }

            //检查店铺资质是否过期
            Wrapper<ShopQualificationDTO> wrapper = new EntityWrapper<>();
            wrapper.eq("shop_id",bo.getShopId());
            List<ShopQualificationDTO> shopQualificationDTOS = shopQualificationService.selectList(wrapper);
            if (CustomizeUtil.listIsNotNull(shopQualificationDTOS)){
                for (ShopQualificationDTO dto : shopQualificationDTOS) {
                    if (dto.getExpireStatus()==2) {
                        if (dto.getType() <= 2) {
                           continue;
                        } else {
                            if (bo.getBrandId().equals(dto.getBrandId())){
                                if (dto.getType()==3){
                                    for (ShopQualificationDTO shopQualificationDTO : shopQualificationDTOS) {
                                        if (shopQualificationDTO.getType()==4 && shopQualificationDTO.getExpireStatus()==2){
                                            continue;
                                        }
                                    }
                                }else {
                                    continue;
                                }
                            }
                        }
                    }
                }
            }

            //处理京东商品直接审核通过并发布
            commodityInfoDTO.setAuditStatus(bo.getAuditStatus());
            commodityInfoDTO.setIsPublish(bo.getIsPublish());
            commodityInfoDTO.setJdFlag(bo.getJdFlag());

            if (StringUtils.isNotBlank(bo.getLogoUrl())) {
                commodityInfoDTO.setLogoUrl(bo.getLogoUrl());
            }
            if (StringUtils.isNotBlank(bo.getLogoUrls())) {
                commodityInfoDTO.setLogoUrls(bo.getLogoUrls());
            }
            if (StringUtils.isNotBlank(bo.getVideoUrls())) {
                commodityInfoDTO.setVideoUrls(bo.getVideoUrls());
            }
            if (StringUtils.isNotBlank(bo.getName())) {
                commodityInfoDTO.setName(bo.getName());
            }
            if (StringUtils.isNotBlank(bo.getDescription())) {
                commodityInfoDTO.setDescription(bo.getDescription());
            }
            if (StringUtils.isNotBlank(bo.getJdPageNum())) {
                commodityInfoDTO.setJdPageNum(bo.getJdPageNum());
            }
            if (null != bo.getSendAreaId()) {
                commodityInfoDTO.setSendAreaId(bo.getSendAreaId());
            }
            if (StringUtils.isNotBlank(bo.getAvailableArea())) {
                commodityInfoDTO.setAvailableArea(bo.getAvailableArea());
            }
            if (null != bo.getSendDays()) {
                commodityInfoDTO.setSendDays(bo.getSendDays());
            }
            if (null != bo.getType()) {
                commodityInfoDTO.setType(bo.getType());
                if (bo.getType() != 1) {
                    commodityInfoDTO.setPayType(ZERO);//全额
                } else {
                    commodityInfoDTO.setPayType(ONE);//分期
                }
            }
            if (null != bo.getShopId()) {
                commodityInfoDTO.setShopId(bo.getShopId());
            }
            if (null != bo.getBrandId()) {
                commodityInfoDTO.setBrandId(bo.getBrandId());
            }
            if (null != bo.getCategoryId()) {
                commodityInfoDTO.setCategoryId(bo.getCategoryId());
            }
            if (StringUtils.isNotBlank(bo.getNotes())) {
                commodityInfoDTO.setNotes(bo.getNotes());
            }
            if (null != bo.getIsRecommend()) {
                commodityInfoDTO.setIsRecommend(bo.getIsRecommend());
            }
            if (null != bo.getIsNew()) {
                commodityInfoDTO.setIsNew(bo.getIsNew());
            }
            if (null != bo.getIsTreasure()) {
                commodityInfoDTO.setIsTreasure(bo.getIsTreasure());
            }
            if (null != bo.getWarrantyMonth()) {
                commodityInfoDTO.setWarrantyMonth(bo.getWarrantyMonth());
            }
            if (StringUtils.isNotBlank(bo.getProductSpecificationUrl())) {
                commodityInfoDTO.setProductSpecificationUrl(bo.getProductSpecificationUrl());
            }
            if(StringUtils.isEmpty(bo.getCommodityNumber())){
                commodityInfoDTO.setCommodityNumber(OrderNumberUtils.getOrderNumber());
            }else{
                commodityInfoDTO.setCommodityNumber(bo.getCommodityNumber());
            }

            if (StringUtils.isNotBlank(bo.getProductCertificateUrls())) {
                commodityInfoDTO.setProductCertificateUrls(bo.getProductCertificateUrls());
            }
            if (null != bo.getIsVipDiscounts()) {
                commodityInfoDTO.setIsVipDiscounts(bo.getIsVipDiscounts());
            }
            if (null != bo.getFirstBalance()) {
                commodityInfoDTO.setFirstBalance(bo.getFirstBalance());
            }
            if (null != bo.getTailBalance()) {
                commodityInfoDTO.setTailBalance(bo.getTailBalance());
            }
            if (null != bo.getSellerAddressId()) {
                commodityInfoDTO.setSellerAddressId(bo.getSellerAddressId());
            }
            if (null != bo.getIsInquiry()) {
                commodityInfoDTO.setIsInquiry(bo.getIsInquiry());
            }
            if (StringUtils.isNotBlank(bo.getFilterIds())) {
                commodityInfoDTO.setFilterIds(bo.getFilterIds());
            }
            if (StringUtils.isNotBlank(bo.getLabelIds())) {
                commodityInfoDTO.setLabelIds(getIds(bo.getLabelIds()));
            }
            if (bo.getStockDays() != null) {
                commodityInfoDTO.setStockDays(bo.getStockDays());
            }

            commodityInfoDTOList.add(commodityInfoDTO);
            //获取套餐信息
            if (StringUtils.isNotBlank(bo.getCombos())) {
                CommodityComboRelationDTO commodityComboRelationDTO = this.getGoodsCombo(bo.getCombos(), commodityInfoDTO.getId());
                if(null != commodityComboRelationDTO){
                    commodityComboRelationDTOList.add(commodityComboRelationDTO);
                }
            }

        }

        commdityReleaseMap.put("commodityInfoDTOList",commodityInfoDTOList);
        commdityReleaseMap.put("commodityComboRelationDTOList",commodityComboRelationDTOList);
        return commdityReleaseMap;
    }

    private CommodityComboRelationDTO getGoodsCombo(String combos,Long goodsId){
        log.info("套餐信息 : {},商品id : {}", combos, goodsId);
        List<CommodityComboRelationDTO> list = new ArrayList<>();
        List<CommodityComboRelationSaveBO> comboList = JSONObject.parseArray(combos, CommodityComboRelationSaveBO.class);
        if (comboList != null && comboList.size() > 0) {
            CommodityComboRelationSaveBO relationSaveBO = comboList.get(0);
            CommodityComboRelationDTO dto = new CommodityComboRelationDTO();
            dto.setId(ymlConfig.getPkId());
            dto.setCommodityId(goodsId);
            dto.setComboName(relationSaveBO.getComboName());
            if (relationSaveBO.getPrice() != null) {
                dto.setPrice(relationSaveBO.getPrice());
            }
            if (relationSaveBO.getWholesalePrice() != null) {
                dto.setWholesalePrice(relationSaveBO.getWholesalePrice());
            }
            if (relationSaveBO.getOriginalPrice() != null) {
                dto.setOriginalPrice(relationSaveBO.getOriginalPrice());
            }
            dto.setInventoryNumber(relationSaveBO.getInventoryNumber());
            dto.setCommoditySize(relationSaveBO.getCommoditySize());
            dto.setCommoditySizeUnit(relationSaveBO.getCommoditySizeUnit());
            dto.setCommodityUnit(relationSaveBO.getCommodityUnit());
            dto.setInventoryNumberWarning(relationSaveBO.getInventoryNumberWarning());
            if (relationSaveBO.getBatchNumber() != null) {
                dto.setBatchNumber(relationSaveBO.getBatchNumber());
            }
            return dto;
        }
        return null;
    }

    /**
     * @Description: 卖家端产品管理全部产品列表
     * @Author: WangChenYu
     * @Param: [sellerVO]
     * @Date: 2020-10-09 15:10
     */
    @Override
    public Page<CommoditySellerVO> querySellerPageList(CommoditySellerVO sellerVO) {
        Page<CommoditySellerVO> page = new Page<>(sellerVO.getPageNo(), sellerVO.getPageSize());
        List<CommoditySellerVO> list = baseMapper.querySellerPageList(page, sellerVO);
        page.setRecords(list);
        return page;
    }

    /**
     * @Description: 卖家个人中心产品管理审核中的商品列表
     * @Author: WangChenYu
     * @Param: [sellerVO]
     * @Date: 2020-10-09 15:11
     */
    @Override
    public Page<CommoditySellerVO> querySellerReviewList(CommoditySellerVO sellerVO) {
        Page<CommoditySellerVO> page = new Page<>(sellerVO.getPageNo(), sellerVO.getPageSize());
        List<CommoditySellerVO> list = baseMapper.querySellerReviewList(page, sellerVO);
        page.setRecords(list);
        return page;
    }

    @Override
    public Page<CommoditySellerVO> querySellerNotOnGoodsList(CommoditySellerVO sellerVO) {
        Page<CommoditySellerVO> page = new Page<>(sellerVO.getPageNo(), sellerVO.getPageSize());
        List<CommoditySellerVO> list = baseMapper.querySellerNotOnGoodsList(page, sellerVO);
        page.setRecords(list);
        return page;
    }

    @Override
    public Page<CommodityInPutawayVO> querySellerInPutawayList(CommodityInPutawayBO bo) {
        Page<CommodityInPutawayVO> page = new Page<>(bo.getPageNo(), bo.getPageSize());
        List<CommodityInPutawayVO> list = baseMapper.querySellerInPutawayList(page, bo);
        if (list != null && list.size() > 0) {
            for (CommodityInPutawayVO vo : list) {
                Integer totalSales = baseMapper.getOneGoodsTotalSales(vo.getId());
                vo.setTotalSales(totalSales);
            }
        }
        return page.setRecords(list);
    }

    @Override
    public Page<CommodityInventoryVO> querySellerInventoryList(CommodityInventoryBO bo) {
        Page<CommodityInventoryVO> page = new Page<>(bo.getPageNo(), bo.getPageSize());
        List<CommodityInventoryVO> list = baseMapper.querySellerInventoryList(page, bo);
        page.setRecords(list);
        return page;
    }

    @Transactional
    @Override
    public Result<List<String>> update(CommodityReleaseBO bo) {
        Result<List<String>> result = new Result<>();
        //判断店铺是否冻结
        boolean checkShopIsClose = shopInfoService.checkShopIsClose(bo.getShopId());
        if (!checkShopIsClose) {
            result.setCode(CodeEnum.FAIL_COMMODITY_ERROR_340015.getCode());
            result.setMsg(CodeEnum.FAIL_COMMODITY_ERROR_340015.getMsg());
            return result;
        }
        CommodityInfoDTO commodityInfoDTO = new CommodityInfoDTO();
        commodityInfoDTO.setId(bo.getId());
        if (StringUtils.isNotBlank(bo.getLogoUrl())) {
            commodityInfoDTO.setLogoUrl(bo.getLogoUrl());
        }
        if (null != bo.getLogoUrls()) {
            commodityInfoDTO.setLogoUrls(bo.getLogoUrls());
        }
        if (StringUtils.isNotBlank(bo.getVideoUrls())) {
            commodityInfoDTO.setVideoUrls(bo.getVideoUrls());
        }
        if (StringUtils.isNotBlank(bo.getName())) {
            commodityInfoDTO.setName(bo.getName());
        }
        if (StringUtils.isNotBlank(bo.getDescription())) {
            commodityInfoDTO.setDescription(bo.getDescription());
        }
        if (null != bo.getSendAreaId()) {
            commodityInfoDTO.setSendAreaId(bo.getSendAreaId());
        }
        if (StringUtils.isNotBlank(bo.getAvailableArea())) {
            commodityInfoDTO.setAvailableArea(bo.getAvailableArea());
        }
        if (bo.getSendDays() != null) {
            commodityInfoDTO.setSendDays(bo.getSendDays());
        }
        if (StringUtils.isNotBlank(bo.getNotes())) {
            commodityInfoDTO.setNotes(bo.getNotes());
        }
        if (bo.getIsRecommend() != null) {
            commodityInfoDTO.setIsRecommend(bo.getIsRecommend());
        }
        if (bo.getIsNew() != null) {
            commodityInfoDTO.setIsNew(bo.getIsNew());
        }
        if (bo.getIsTreasure() != null) {
            commodityInfoDTO.setIsTreasure(bo.getIsTreasure());
        }
        if (null != bo.getProductSpecificationUrl()) {
            commodityInfoDTO.setProductSpecificationUrl(bo.getProductSpecificationUrl());
        }
        if (StringUtils.isNotBlank(bo.getProductCertificateUrls())) {
            commodityInfoDTO.setProductCertificateUrls(bo.getProductCertificateUrls());
        }
        if (bo.getIsVipDiscounts() != null) {
            commodityInfoDTO.setIsVipDiscounts(bo.getIsVipDiscounts());
        }
        if (bo.getFirstBalance() != null) {
            commodityInfoDTO.setFirstBalance(bo.getFirstBalance());
        }
        if (bo.getTailBalance() != null) {
            commodityInfoDTO.setTailBalance(bo.getTailBalance());
        }
        if (bo.getSellerAddressId() != null) {
            commodityInfoDTO.setSellerAddressId(bo.getSellerAddressId());
        }
        if (bo.getIsInquiry() != null) {
            commodityInfoDTO.setIsInquiry(bo.getIsInquiry());
        }

        if (bo.getStockDays() != null) {
            commodityInfoDTO.setStockDays(bo.getStockDays());
        }
        commodityInfoDTO.setLabelIds(bo.getLabelIds());
        commodityInfoDTO.setFilterIds(bo.getFilterIds());
        //保存商品基本信息
        boolean update = this.updateById(commodityInfoDTO);
        if (!update) {
            result.setCode(CodeEnum.FAIL_COMMODITY_ERROR_340006.getCode());
            result.setMsg(CodeEnum.FAIL_COMMODITY_ERROR_340006.getMsg());
            return result;
        }
        //保存商品规格信息
        if (StringUtils.isNotBlank(bo.getAttrs())) {
            this.updateGoodsAttrs(bo.getAttrs(), commodityInfoDTO.getId());
        }
        //商品套餐信息
        if (StringUtils.isNotBlank(bo.getCombos())) {
            this.updateGoodsCombo(bo.getCombos(), commodityInfoDTO.getId());
        }
        // 修改参数信息
        if (StringUtils.isNotBlank(bo.getParamValues())) {
            this.updateParamValue(bo.getParamValues(), commodityInfoDTO.getId());
        }
        result.setCode(CodeEnum.SUCCESS.getCode());
        result.setMsg(CodeEnum.SUCCESS.getMsg());
        List<CommodityEsVO> commodityEsVOS = this.queryAllESGoodsByCommodityId(commodityInfoDTO.getId());
        if (commodityEsVOS != null && commodityEsVOS.size()>0){
            for (CommodityEsVO commodityEsVO : commodityEsVOS) {
                boolean equals = commodityEsVO.getId().equals(commodityInfoDTO.getId());
                if (equals){
                    List<EsGoodsDTO> esGoods = getEsGoods(commodityEsVO);
                    for (EsGoodsDTO esGood : esGoods) {
                        log.info("更新商品ES------------开始");
                        boolean b = elasticsearchService.saveOrUpdateEntity(esGood,"index_goods_2020","goods",String.valueOf(commodityInfoDTO.getId()));
                        if(b){
                            CommodityInfoDTO dto = new CommodityInfoDTO();
                            dto.setIsSynEs(1);
                            EntityWrapper wrapper = new EntityWrapper();
                            wrapper.eq("id",esGood.getId());
                            this.update(dto,wrapper);
                        }
                        log.info("更新商品ES------------结束");
                    }
                }
            }
        }
        return result;
    }

    @Override
    public Result<List<String>> deletePhysical(Long id) {
        Result<List<String>> result = new Result<>();
        CommodityInfoDTO dto = this.selectById(id);
        if (dto == null) {
            result.setCode(CodeEnum.FAIL_COMMODITY_ERROR_340000.getCode());
            result.setMsg(CodeEnum.FAIL_COMMODITY_ERROR_340000.getMsg());
            return result;
        }
        //判断店铺是否冻结
        boolean checkShopIsClose = shopInfoService.checkShopIsClose(dto.getShopId());
        if (!checkShopIsClose) {
            result.setCode(CodeEnum.FAIL_COMMODITY_ERROR_340015.getCode());
            result.setMsg(CodeEnum.FAIL_COMMODITY_ERROR_340015.getMsg());
            return result;
        }
        CommodityInfoDTO deleteDTO = new CommodityInfoDTO();
        deleteDTO.setId(dto.getId());
        deleteDTO.setIsRemove(ONE);
        boolean update = this.updateById(deleteDTO);
        if (!update) {
            result.setCode(CodeEnum.FAIL_100009.getCode());
            result.setMsg(CodeEnum.FAIL_100009.getMsg());
            return result;
        }
        result.setCode(CodeEnum.SUCCESS.getCode());
        result.setMsg(CodeEnum.SUCCESS.getMsg());
        return result;
    }

    @Override
    public CommodityPriceVO getByIdOtherInterface(Long id) {
        return baseMapper.getByIdOtherInterface(id);
    }

    @Override
    public CommodityDetailsVO getCommodityDetails(Long id) {
        CommodityDetailsVO details = baseMapper.getCommodityDetails(id);
        if (details.getSendAreaId() != null) {
            String names = "";
            String areaName = this.packageShippingArea(details.getSendAreaId(), names);
            details.setSendAreaName(areaName);
        }
        return details;
    }


    @Override
    public Integer getCountSales(Long goodsId,Long shopId) {
        return baseMapper.getCountSales(goodsId,shopId);
    }

    @Override
    public List<CommoditySimilarVO> getSimilarCommodity(Long id) {
        return baseMapper.getSimilarCommodity(id);
    }

    @Override
    public Integer getCommodityNumByShopId(Long shopId) {
        Wrapper<CommodityInfoDTO> wrapper = new EntityWrapper<>();
        wrapper.eq("shop_id", shopId);
        wrapper.in("is_publish", "0,1"); //上架;0未上架、1已上架
        wrapper.eq("status", 0);
        wrapper.eq("audit_status", 1);
        return this.selectCount(wrapper);
    }

    @Override
    public Integer getShopCommodityIsNew(Long shopId) {
        Wrapper<CommodityInfoDTO> wrapper = new EntityWrapper<>();
        wrapper.eq("shop_id", shopId);
        wrapper.eq("is_publish", 1); //上架;0未上架、1已上架
        wrapper.eq("is_new", 1); //是否新品上架;0否、1是
        return this.selectCount(wrapper);
    }

    /**
     * @Description: 根据品牌id查询商品, 批量下架商品
     * @Author: WangChenYu
     * @Param: [shopId, brandId]
     * @Date: 2020-10-10 11:46
     */
    @Override
    public void updateBatchPublishByShopBrand(Long shopId, Long brandId) {
        List<CommodityInfoDTO> list = new ArrayList<>();
        Wrapper<CommodityInfoDTO> wrapper = new EntityWrapper<>();
        wrapper.eq("brand_id", brandId);
        wrapper.eq("shop_id", shopId);
        List<CommodityInfoDTO> goodsList = this.selectList(wrapper);
        if (goodsList != null && goodsList.size() > 0) {
            for (CommodityInfoDTO infoDTO : goodsList) {
                CommodityInfoDTO dto = new CommodityInfoDTO();
                dto.setIsPublish(0);
                dto.setId(infoDTO.getId());
                list.add(dto);
            }
            this.updateBatchById(list);
        }
    }

    @Override
    public List<CommodityInfoDTO> queryByIds(String ids) {
        List<String> list = Arrays.asList(ids.split(","));
        return baseMapper.queryByIds(list);
    }

    /**
     * @Description: 查询卖家个人中心商品回收站列表
     * @Author: WangChenYu
     * @Param: [bo]
     * @Date: 2020-10-10 11:46
     */
    @Override
    public Page<CommodityRecycleBinVO> querySellerRecycleBinList(CommodityRecycleBinBO bo) {
        Page<CommodityRecycleBinVO> page = new Page<>(bo.getPageNo(), bo.getPageSize());
        List<CommodityRecycleBinVO> list = baseMapper.querySellerRecycleBinList(page, bo);
        page.setRecords(list);
        return page;
    }

    /**
     * @Description: 批量逻辑删除商品
     * @Author: WangChenYu
     * @Param: [ids]
     * @Date: 2020-10-10 11:45
     */
    @Override
    public Result<List<String>> deleteLogicBatch(String ids) {
        Result<List<String>> result = new Result<>();
        String[] arr = ids.split(",");
        List<String> strings = Arrays.asList(arr);
        List<Long> newIds = new ArrayList<>();//新品推荐ids
        List<Long> rm = new ArrayList<>();//掌柜推荐
        List<Long> shopByby = new ArrayList<>();//镇店之宝
        if (strings.size() > 0) {
            List<CommodityInfoDTO> list = new ArrayList<>();
            for (String id : strings) {
                CommodityInfoDTO dto = this.selectById(id);
                dto.setStatus(ONE);
                list.add(dto);

                //从es中删除
                //searchService.deleteData("index_goods_2020", "goods", dto.getId().toString());

                //判断商品是否掌柜推荐 0否、1是
                if (dto.getIsRecommend() == ONE) {
                    rm.add(dto.getId());
                }
                // 是否新品上架 0否、1是
                if (dto.getIsNew() == ONE) {
                    newIds.add(dto.getId());
                }
                // 是否镇店之宝 0否、1是
                if (dto.getIsTreasure() == ONE) {
                    shopByby.add(dto.getId());
                }
            }
            boolean update = this.updateBatchById(list);
            if (update) {
                //判断商品是否掌柜推荐 0否、1是
                iEpgShopSectionService.deleteShopSectionBySectionType(rm, list.get(ZERO).getShopId(),
                        ShoppingCodeEnum.SHOPPER_RECOMMEND_3.getMsg());
                // 是否新品上架 0否、1是
                iEpgShopSectionService.deleteShopSectionBySectionType(newIds, list.get(ZERO).getShopId(),
                        ShoppingCodeEnum.NEW_SHOP_1.getMsg());
                // 是否镇店之宝 0否、1是
                iEpgShopSectionService.deleteShopSectionBySectionType(shopByby, list.get(ZERO).getShopId(),
                        ShoppingCodeEnum.SHOP_BABY_2.getMsg());
                result.setCode(CodeEnum.SUCCESS.getCode());
                result.setMsg(CodeEnum.SUCCESS.getMsg());
            } else {
                result.setCode(CodeEnum.FAIL_100009.getCode());
                result.setMsg(CodeEnum.FAIL_100009.getMsg());
            }
            List<EsShopDTO> esShop = iShopInfoService.queryEsShop(list.get(ZERO).getShopId().toString());
            shopSearchService.updateShop(list.get(ZERO).getShopId().toString(), "index_shop_2020", "", 0, esShop.size(), esShop);
            return result;
        }

        result.setCode(CodeEnum.FAIL_100009.getCode());
        result.setMsg(CodeEnum.FAIL_100009.getMsg());
        return result;
    }

    /**
     * @Description: 批量恢复商品
     * @Author: WangChenYu
     * @Param: [ids]
     * @Date: 2020-10-10 11:44
     */
    @Override
    public Result<List<String>> updateBatchRestore(String ids) {
        Result<List<String>> result = new Result<>();
        String[] arr = ids.split(",");
        List<String> strings = Arrays.asList(arr);
        if (strings.size() > 0) {
            List<CommodityInfoDTO> list = new ArrayList<>();
            for (String id : strings) {
                CommodityInfoDTO dto = this.selectById(id);
                if (dto.getIsPlatformRemove() == ONE) {
                    result.setCode(CodeEnum.FAIL_COMMODITY_ERROR_340016.getCode());
                    result.setMsg(CodeEnum.FAIL_COMMODITY_ERROR_340016.getMsg());
                    return result;
                }
                dto.setStatus(ZERO);
                list.add(dto);

                // 将商品添加进ES
//                CommodityEsVO goods = baseMapper.queryESGoodsById(dto.getId());
//                List<EsGoodsDTO> esGoods = this.getEsGoods(goods);
//                searchService.addGoods("index_goods_2020", "goods", 0, esGoods.size(), esGoods);
            }
            boolean update = this.updateBatchById(list);
            if (update) {
                result.setCode(CodeEnum.SUCCESS.getCode());
                result.setMsg(CodeEnum.SUCCESS.getMsg());
            } else {
                result.setCode(CodeEnum.FAIL_COMMODITY_ERROR_340008.getCode());
                result.setMsg(CodeEnum.FAIL_COMMODITY_ERROR_340008.getMsg());
            }
            List<EsShopDTO> esShop = iShopInfoService.queryEsShop(list.get(ZERO).getShopId().toString());
            shopSearchService.updateShop(list.get(ZERO).getShopId().toString(), "index_shop_2020", "", 0, esShop.size(), esShop);
            return result;
        }
        result.setCode(CodeEnum.FAIL_COMMODITY_ERROR_340008.getCode());
        result.setMsg(CodeEnum.FAIL_COMMODITY_ERROR_340008.getMsg());
        return result;
    }

    /**
     * @Description: 批量上架商品
     * @Author: WangChenYu
     * @Param: [ids]
     * @Date: 2020-10-10 11:43
     */
    @Override
    public Result<List<String>> updateBatchUpFrame(String ids) {
        Result<List<String>> result = new Result<>();
        String[] arr = ids.split(",");
        List<String> strings = Arrays.asList(arr);
        List<Long> newIds = new ArrayList<>();//新品推荐ids
        List<Long> rm = new ArrayList<>();//掌柜推荐
        List<Long> shopByby = new ArrayList<>();//镇店之宝
        if (strings.size() > 0) {
            List<CommodityInfoDTO> list = new ArrayList<>();
            for (String id : strings) {
                CommodityInfoDTO dto = this.selectById(id);
                //判断是否由平台下架
                if (dto.getIsPlatformShelf() == ONE) {
                    result.setCode(CodeEnum.FAIL_COMMODITY_ERROR_340002.getCode());
                    result.setMsg(CodeEnum.FAIL_COMMODITY_ERROR_340002.getMsg());
                    return result;
                }
                boolean expireStatus = shopQualificationService.getExpireStatus(dto.getShopId(), dto.getBrandId());
                if (!expireStatus) {
                    result.setCode(CodeEnum.FAIL_COMMODITY_ERROR_340013.getCode());
                    result.setMsg(CodeEnum.FAIL_COMMODITY_ERROR_340013.getMsg());
                    return result;
                }
                // 检查店铺变更类目品牌
                boolean checkShopCategoryBrand = this.checkShopCategoryBrand(dto);
                if (!checkShopCategoryBrand) {
                    return new Result<>(CodeEnum.FAIL_COMMODITY_ERROR_340017);
                }
                dto.setIsPublish(ONE);//上架
                // 将商品添加进ES
                CommodityEsVO goods = baseMapper.queryESGoodsById(dto.getId());
                List<EsGoodsDTO> esGoods = this.getEsGoods(goods);
                searchService.addGoods("index_goods_2020", "goods", 0, esGoods.size(), esGoods);
                list.add(dto);
                //判断商品是否掌柜推荐 0否、1是
                if (dto.getIsRecommend() == ONE) {
                    rm.add(dto.getId());
                }
                // 是否新品上架 0否、1是
                if (dto.getIsNew() == ONE) {
                    newIds.add(dto.getId());
                }
                // 是否镇店之宝 0否、1是
                if (dto.getIsTreasure() == ONE) {
                    shopByby.add(dto.getId());
                }
            }
            boolean update = this.updateBatchById(list);
            if (update) {
                //判断商品是否掌柜推荐 0否、1是
                iEpgShopSectionService.addShopSectionBySectionType(rm, list.get(ZERO).getShopId(),
                        ShoppingCodeEnum.SHOPPER_RECOMMEND_3.getMsg());
                // 是否新品上架 0否、1是
                iEpgShopSectionService.addShopSectionBySectionType(newIds, list.get(ZERO).getShopId(),
                        ShoppingCodeEnum.NEW_SHOP_1.getMsg());
                // 是否镇店之宝 0否、1是
                iEpgShopSectionService.addShopSectionBySectionType(shopByby, list.get(ZERO).getShopId(),
                        ShoppingCodeEnum.SHOP_BABY_2.getMsg());
                result.setCode(CodeEnum.SUCCESS.getCode());
                result.setMsg(CodeEnum.SUCCESS.getMsg());
            } else {
                result.setCode(CodeEnum.FAIL_COMMODITY_ERROR_340003.getCode());
                result.setMsg(CodeEnum.FAIL_COMMODITY_ERROR_340003.getMsg());
            }
            return result;
        }
        result.setCode(CodeEnum.FAIL_COMMODITY_ERROR_340003.getCode());
        result.setMsg(CodeEnum.FAIL_COMMODITY_ERROR_340003.getMsg());
        return result;
    }

    /**
     * @Description: 批量下架商品
     * @Author: WangChenYu
     * @Param: [ids]
     * @Date: 2020-10-10 11:43
     */
    @Override
    public Result<List<String>> updateBatchDownFrame(String ids) {
        Result<List<String>> result = new Result<>();
        String[] arr = ids.split(",");
        List<String> strings = Arrays.asList(arr);
        List<Long> newIds = new ArrayList<>();//新品推荐ids
        List<Long> rm = new ArrayList<>();//掌柜推荐
        List<Long> shopByby = new ArrayList<>();//镇店之宝
        if (strings.size() > 0) {
            List<CommodityInfoDTO> list = new ArrayList<>();
            for (String id : strings) {
                CommodityInfoDTO dto = this.selectById(id);
                dto.setIsPublish(ZERO);
                //从es中删除
                searchService.deleteData("index_goods_2020", "goods", dto.getId().toString());
                list.add(dto);
                //判断商品是否掌柜推荐 0否、1是
                if (dto.getIsRecommend() == ONE) {
                    rm.add(dto.getId());
                }
                // 是否新品上架 0否、1是
                if (dto.getIsNew() == ONE) {
                    newIds.add(dto.getId());
                }
                // 是否镇店之宝 0否、1是
                if (dto.getIsTreasure() == ONE) {
                    shopByby.add(dto.getId());
                }
            }
            boolean update = this.updateBatchById(list);
            if (update) {
                //判断商品是否掌柜推荐 0否、1是
                iEpgShopSectionService.deleteShopSectionBySectionType(rm, list.get(ZERO).getShopId(),
                        ShoppingCodeEnum.SHOPPER_RECOMMEND_3.getMsg());
                // 是否新品上架 0否、1是
                iEpgShopSectionService.deleteShopSectionBySectionType(newIds, list.get(ZERO).getShopId(),
                        ShoppingCodeEnum.NEW_SHOP_1.getMsg());
                // 是否镇店之宝 0否、1是
                iEpgShopSectionService.deleteShopSectionBySectionType(shopByby, list.get(ZERO).getShopId(),
                        ShoppingCodeEnum.SHOP_BABY_2.getMsg());
                result.setCode(CodeEnum.SUCCESS.getCode());
                result.setMsg(CodeEnum.SUCCESS.getMsg());
            } else {
                result.setCode(CodeEnum.FAIL_COMMODITY_ERROR_340004.getCode());
                result.setMsg(CodeEnum.FAIL_COMMODITY_ERROR_340004.getMsg());
            }
            return result;
        }
        result.setCode(CodeEnum.FAIL_COMMODITY_ERROR_340004.getCode());
        result.setMsg(CodeEnum.FAIL_COMMODITY_ERROR_340004.getMsg());
        return result;
    }

    /**
     * @Description: 根据商品id，查询商品套餐情况
     * @Author: WangChenYu
     * @Param: [goodsId]
     * @Date: 2020-10-10 11:43
     */
    @Override
    public List<CommodityComboRelationVO> queryGoodsComboMsg(Long goodsId) {
        return baseMapper.queryGoodsComboMsg(goodsId);
    }

    /**
     * @Description: 查询购物车信息，供zhanghualang使用
     * @Author: WangChenYu
     * @Param: [goodsId, atrrIds]
     * @Date: 2020-10-10 11:43
     */
    @Override
    public CommodityAttrPriceVO getShoppingCartGoods(Long goodsId, String attributesIds) {
        //给商品规格属性id排序
        String ids = getIds(attributesIds);
        //先查规格属性
        CommodityAttrPriceVO sku = commoditySpecificationRelationService.getGoodsSkuPrice(goodsId, ids);
        if (null != sku && null != sku.getId()) {
            return sku;
        } else {
            if (ids.contains(",")) {
                return new CommodityAttrPriceVO();
            } else {
                //查询套餐
                CommodityComboRelationVO comboRelationVO = commodityComboRelationService.getByGoodsIdAndComboId(goodsId, Long.valueOf(ids));
                if (null != comboRelationVO && null != comboRelationVO.getId()) {
                    CommodityAttrPriceVO attrPriceVO = new CommodityAttrPriceVO();
                    attrPriceVO.setId(comboRelationVO.getId());
                    attrPriceVO.setAttrIds(String.valueOf(comboRelationVO.getId()));
                    attrPriceVO.setGoodsId(comboRelationVO.getCommodityId());
                    attrPriceVO.setTaxRate(comboRelationVO.getTaxRate());
                    attrPriceVO.setPrice(comboRelationVO.getPrice());
                    attrPriceVO.setWholesalePrice(comboRelationVO.getWholesalePrice());
                    attrPriceVO.setInventoryNumber(comboRelationVO.getInventoryNumber());
                    attrPriceVO.setCommoditySize(comboRelationVO.getCommoditySize());
                    attrPriceVO.setCommoditySizeUnit(comboRelationVO.getCommoditySizeUnit());
                    attrPriceVO.setCommodityUnit(comboRelationVO.getCommodityUnit());
                    attrPriceVO.setInventoryNumberWarning(comboRelationVO.getInventoryNumberWarning());
                    attrPriceVO.setBatchNumber(comboRelationVO.getBatchNumber());
                    attrPriceVO.setAtrrNames(comboRelationVO.getComboName());
                    attrPriceVO.setUnitName(comboRelationVO.getUnitName());
                    return attrPriceVO;
                }
            }
        }
        return new CommodityAttrPriceVO();
    }

    /**
     * description: 保存商品规格信息
     * param: [attrs]
     * author: chenyu.wang
     * date: 2020-06-15
     * return: void
     */
    private void saveGoodsAttrs(String attrs, Long goodsId) {
        log.info("规格属性 : {},商品id : {}", attrs, goodsId);
        List<CommoditySpecificationRelationDTO> list = new ArrayList<>();
        List<CommoditySpecificationRelationSaveBO> ids = JSONObject.parseArray(attrs, CommoditySpecificationRelationSaveBO.class);
        if (ids != null && ids.size() > 0) {
            for (CommoditySpecificationRelationSaveBO saveBO : ids) {
                CommoditySpecificationRelationDTO dto = new CommoditySpecificationRelationDTO();
                //商品规格属性ids排序
                String skuIds = getIds(saveBO.getAttrIds());
                dto.setCommodityId(goodsId);
                dto.setAttrIds(skuIds);
                dto.setId(ymlConfig.getPkId());
                if (saveBO.getPrice() != null) {
                    dto.setPrice(saveBO.getPrice());
                }
                if (saveBO.getWholesalePrice() != null) {
                    dto.setWholesalePrice(saveBO.getWholesalePrice());
                }
                if (saveBO.getOriginalPrice() != null) {
                    dto.setOriginalPrice(saveBO.getOriginalPrice());
                }
                dto.setInventoryNumber(saveBO.getInventoryNumber());
                dto.setCommoditySize(saveBO.getCommoditySize());
                dto.setCommoditySizeUnit(saveBO.getCommoditySizeUnit());
                dto.setCommodityUnit(saveBO.getCommodityUnit());
                dto.setInventoryNumberWarning(saveBO.getInventoryNumberWarning());
                if (saveBO.getBatchNumber() != null) {
                    dto.setBatchNumber(saveBO.getBatchNumber());
                }
                dto.setAtrrNames(saveBO.getAtrrNames());
                list.add(dto);
                //将商品库存放入reids
                redisUtil.saveCommodityNum(goodsId, skuIds, saveBO.getInventoryNumber());
            }
            //保存商品规格信息
            commoditySpecificationRelationService.insertBatch(list);
        }
    }

    /**
     * description: 保存商品套餐信息
     * param: [combos]
     * author: chenyu.wang
     * date: 2020-06-15
     * return: void
     */
    private void saveGoodsCombo(String combos, Long goodsId) {
        log.info("套餐信息 : {},商品id : {}", combos, goodsId);
        List<CommodityComboRelationDTO> list = new ArrayList<>();
        List<CommodityComboRelationSaveBO> comboList = JSONObject.parseArray(combos, CommodityComboRelationSaveBO.class);
        if (comboList != null && comboList.size() > 0) {
            for (CommodityComboRelationSaveBO relationSaveBO : comboList) {
                CommodityComboRelationDTO dto = new CommodityComboRelationDTO();
                dto.setId(ymlConfig.getPkId());
                dto.setCommodityId(goodsId);
                dto.setComboName(relationSaveBO.getComboName());
                if (relationSaveBO.getPrice() != null) {
                    dto.setPrice(relationSaveBO.getPrice());
                }
                if (relationSaveBO.getWholesalePrice() != null) {
                    dto.setWholesalePrice(relationSaveBO.getWholesalePrice());
                }
                if (relationSaveBO.getOriginalPrice() != null) {
                    dto.setOriginalPrice(relationSaveBO.getOriginalPrice());
                }
                dto.setInventoryNumber(relationSaveBO.getInventoryNumber());
                dto.setCommoditySize(relationSaveBO.getCommoditySize());
                dto.setCommoditySizeUnit(relationSaveBO.getCommoditySizeUnit());
                dto.setCommodityUnit(relationSaveBO.getCommodityUnit());
                dto.setInventoryNumberWarning(relationSaveBO.getInventoryNumberWarning());
                if (relationSaveBO.getBatchNumber() != null) {
                    dto.setBatchNumber(relationSaveBO.getBatchNumber());
                }
                list.add(dto);
                //将商品库存放入reids
                redisUtil.saveCommodityNum(goodsId, dto.getId().toString(), relationSaveBO.getInventoryNumber());
            }
            //保存商品套餐信息
            commodityComboRelationService.insertBatch(list);
        }
    }

    /**
     * description: 保存商品参数信息
     * param: [values, goodsId]
     * author: chenyu.wang
     * date: 2020-06-15
     * return: void
     */
    private void saveParamValue(String values, Long goodsId) {
        log.info("参数信息 : {},商品id : {}", values, goodsId);
        List<CommodityParamValueRelationDTO> list = new ArrayList<>();
        List<CommodityParamValueRelationSaveBO> saveList = JSON.parseArray(values, CommodityParamValueRelationSaveBO.class);
        if (saveList != null && saveList.size() > 0) {
            for (CommodityParamValueRelationSaveBO bo : saveList) {
                CommodityParamValueRelationDTO dto = new CommodityParamValueRelationDTO();
                dto.setId(ymlConfig.getPkId());
                dto.setCommodityId(goodsId);
                dto.setParamId(bo.getParamId());
                dto.setParamValueIds(bo.getParamValueIds());
                list.add(dto);
            }
            commodityParamValueRelationService.insertBatch(list);
        }
    }

    /**
     * @Description: 保存商品销售属性
     * @Author: chenyu.wang
     * @Params: [salesAttributes, goodsId]
     * @Date: 2020.11.16 14:45
     */
    private void saveSalesAttributes(String salesAttributes, Long goodsId) {
        log.info("商品销售属性 : {}", salesAttributes);
        List<CommoditySalesAttributesRelationSaveBO> saveList = JSON.parseArray(salesAttributes, CommoditySalesAttributesRelationSaveBO.class);
        if (!isNull(saveList)) {
            for (CommoditySalesAttributesRelationSaveBO saveBO : saveList) {
                saveBO.setCommodityId(goodsId);
                commoditySalesAttributesRelationService.add(saveBO);
            }
        }
    }

    @Override
    public List<CommodityPriceVO> getHighShop(List<OrderHighShopVo> orderHighShop) {
        List<CommodityPriceVO> commodityPriceVOS = new ArrayList<>();
        for (OrderHighShopVo orderHighShopVo : orderHighShop) {
            CommodityPriceVO commodityPriceVO = getByIdOtherInterface(orderHighShopVo.getId());
            commodityPriceVOS.add(commodityPriceVO);
        }
        return commodityPriceVOS;
    }

    /**
     * @Description: 后台管理系统产品列表
     * @Author: WangChenYu
     * @Param: [bo]
     * @Date: 2020-10-10 11:42
     */
    @Override
    public Page<CommodityAdminListVO> queryAdminPageList(CommodityAdminListBO bo) {
        log.info("start----------------------------");
        Page<CommodityAdminListVO> page = new Page<>(bo.getPageNo(), bo.getPageSize());
        List<CommodityAdminListVO> list;
        if (bo.getGetType() == null) {
            bo.setGetType(TWO);
        }
        log.info("start---------------2-------------");
        if (bo.getGetType() == ONE) {
            //代客下单列表
            list = baseMapper.queryAdminValetOrderGoodsList(page, bo);
            if (!isNull(list)) {
                for (CommodityAdminListVO vo : list) {
                    String goodsCategoryName = commodityCategoryService.creatTreeById(vo.getCategoryId(), "");
                    if (StringUtils.isNotBlank(goodsCategoryName)) {
                        vo.setGoodsCategoty(goodsCategoryName);
                    }
                }
            }
        } else {
            log.info("开始---------------------");
            list = baseMapper.queryAdminPageList(page, bo);
            log.info("中间---------------------");
            if (!isNull(list)) {
                for (CommodityAdminListVO vo : list) {
                    String goodsCategoryName = commodityCategoryService.creatTreeById(vo.getCategoryId(), "");
                    if (StringUtils.isNotBlank(goodsCategoryName)) {
                        vo.setGoodsCategoty(goodsCategoryName);
                    }
                }
            }
            log.info("结束---------------------");
        }
        page.setRecords(list);
        return page;
    }

    /**
     * @Description: 查询产品详情
     * @Author: WangChenYu
     * @Param: [id]
     * @Date: 2020-10-09 15:12
     */
    @Override
    public CommodityRegardVO queryCenterGoodsDetails(Long id) {
        CommodityRegardVO details = baseMapper.queryCenterGoodsDetails(id);
        if (null == details) {
            return null;
        }
        //封装商品发货区域信息
        if (details.getSendAreaId() != null) {
            String names = "";
            String area = this.packageShippingArea(details.getSendAreaId(), names);
            details.setSendAreaName(area);
        }
        //获取商品筛选属性
        if (StringUtils.isNotBlank(details.getFilterIds())) {
            List<CommodityFilterOneVO> filterList = commodityFilterAttributesService.creatTree(details.getFilterIds());
            if (!isNull(filterList)) {
                details.setFilterList(filterList);
            }
        } else {
            List<CommodityFilterOneVO> realTopList = new ArrayList<>();
            //获取商品关联类目的最顶级类目
            CommodityCategoryDTO topCategory = this.getTopCategory(details.getCategoryId());
            if (topCategory != null) {
                String filterName = null;
                List<CommodityFilterAttributesNewVO> filterAttributes = commodityCategoryService.getFilterAttributes(topCategory.getId(), filterName);
                if (!isNull(filterAttributes)) {
                    for (CommodityFilterAttributesNewVO filterAttribute : filterAttributes) {
                        CommodityFilterOneVO filterOneVO = new CommodityFilterOneVO();
                        filterOneVO.setId(filterAttribute.getId());
                        filterOneVO.setParentId(filterAttribute.getParentId());
                        filterOneVO.setFilterName(filterAttribute.getFilterName());
                        realTopList.add(filterOneVO);
                    }
                    details.setFilterList(realTopList);
                }
            }
        }
        //获取商品参数信息
        List<CommodityParamValueRelationVO> paramDetails = baseMapper.queryGoodsParamDetails(id);
        if (!isNull(paramDetails)) {
            details.setParamList(paramDetails);
        }
        // 获取商品选择的销售属性
        List<CommoditySalesAttributesRelationVO> salesAttributes = commoditySalesAttributesRelationService.queryGoodsSalesAttributes(id);
        if (!isNull(salesAttributes)) {
            details.setSalesAttributes(salesAttributes);
        }
        // 获取商品标签信息
        if (StringUtils.isNotBlank(details.getLabelIds())) {
            List<CommodityLabelDTO> labels = new ArrayList<>();
            String[] ids = details.getLabelIds().split(",");
            for (String s : ids) {
                CommodityLabelDTO selectById = commodityLabelService.selectById(s);
                if (selectById != null) {
                    labels.add(selectById);
                }
            }
            details.setLabelList(labels);
        }
        return details;
    }

    /**
     * @Description: 后台管理系统查看产品详情
     * @Author: WangChenYu
     * @Param: [id]
     * @Date: 2020-10-10 09:35
     */
    @Override
    public CommodityRegardVO queryAdminCenterGoodsDetails(Long id) {
        CommodityRegardVO details = baseMapper.queryCenterGoodsDetails(id);
        //封装商品发货区域信息
        if (details.getSendAreaId() != null) {
            String names = "";
            String area = this.packageShippingArea(details.getSendAreaId(), names);
            details.setSendAreaName(area);
        }
        //获取商品筛选属性
        if (StringUtils.isNotBlank(details.getFilterIds())) {
            List<CommodityFilterOneVO> filterList = commodityFilterAttributesService.creatTree(details.getFilterIds());
            if (!isNull(filterList)) {
                filterList.removeIf(filterOneVo -> isNull(filterOneVo.getChildList()));
                details.setFilterList(filterList);
            }
        }
        //获取商品参数信息
        List<CommodityParamValueRelationVO> paramDetails = baseMapper.queryGoodsParamDetails(id);
        if (!isNull(paramDetails)) {
            details.setParamList(paramDetails);
        }
        // 获取商品标签信息
        if (StringUtils.isNotBlank(details.getLabelIds())) {
            List<CommodityLabelDTO> labels = new ArrayList<>();
            String[] ids = details.getLabelIds().split(",");
            for (String s : ids) {
                CommodityLabelDTO selectById = commodityLabelService.selectById(s);
                if (selectById != null) {
                    labels.add(selectById);
                }
            }
            details.setLabelList(labels);
        }
        return details;
    }

    /**
     * @Description: 后台管理系统审核商品
     * @Author: WangChenYu
     * @Param: [id, userId, text, state]
     * @Date: 2020-10-10 11:42
     */
    @Override
    public Result updateAuditCommodity(Long id, Long userId, String text, Integer state) {
        log.info("id : {},userId : {},test : {},state : {}", id, userId, text, state);
        CommodityInfoDTO dto = this.selectById(id);
        if (null == dto) {
            return new Result<>(CodeEnum.FAIL_COMMODITY_AUDIT_330000);
        }

        CommodityInfoDTO commodityInfoDTO = baseMapper.selectById (id);
        if (commodityInfoDTO.getAuditStatus () == 1 || commodityInfoDTO.getAuditStatus () == 2 || commodityInfoDTO.getAuditStatus () == 3){
            return new Result<>(CodeEnum.FAIL_COMMODITY_AUDIT_330000);
        }
        CommodityInfoDTO updateDto = new CommodityInfoDTO();
        updateDto.setId(dto.getId());
        updateDto.setAuditStatus(state);//审核 0审核中，1审核通过，2审核打回，3审核不通过,4重新提交
        updateDto.setReturnReason(text);//打回原因
        if (state == 2) {
            updateDto.setIsPassLook(0);
        }
        if (state == 1){
            //检查店铺资质是否过期
            updateDto.setIsPublish(1);
            Wrapper<ShopQualificationDTO> shopQualificationDTOEntityWrapper = new EntityWrapper<>();
            shopQualificationDTOEntityWrapper.eq("shop_id",dto.getShopId());
            List<ShopQualificationDTO> shopQualificationDTOS = shopQualificationService.selectList(shopQualificationDTOEntityWrapper);
            if (CustomizeUtil.listIsNotNull(shopQualificationDTOS)){
                for (ShopQualificationDTO shopQualificationDTO : shopQualificationDTOS) {
                    if (shopQualificationDTO.getExpireStatus()==2) {
                        if (shopQualificationDTO.getType() <= 2) {
                            updateDto.setIsPublish(0);
                        } else {

                                if (shopQualificationDTO.getBrandId().equals(dto.getBrandId())){
                                    if (shopQualificationDTO.getType()==3){
                                        for (ShopQualificationDTO qualificationDTO : shopQualificationDTOS) {
                                            if (qualificationDTO.getType()==4 && qualificationDTO.getExpireStatus()==2){
                                                updateDto.setIsPublish(0);
                                            }
                                        }
                                    }else {
                                        updateDto.setIsPublish(0);
                                    }

                                }


                        }
                    }
                }
            }

        }
        boolean update = this.updateById(updateDto);
        if (!update) {
            return new Result<>(CodeEnum.FAIL_COMMODITY_AUDIT_330000);
        }
        if (state == 1){
            CommodityEsVO goods = baseMapper.queryESGoodsById(dto.getId());
            List<EsGoodsDTO> esGoods = this.getEsGoods(goods);
            searchService.addGoods("index_goods_2020", "goods", 0, esGoods.size(), esGoods);
        }
        String content;
        if (state == 2) {
            content = "您上传的商品有违规项,现已打回修改。";
        } else {
            content = "您上传的商品已审核通过。";
            text = "您上传的商品已审核通过";
        }
        List<EsShopDTO> esShop = iShopInfoService.queryEsShop(dto.getShopId().toString());
        shopSearchService.updateShop(dto.getShopId().toString(), "index_shop_2020", "", 0, esShop.size(), esShop);
        this.sendMsg(dto.getShopId(), content, text, 0L, 2);
        //保存审核日志
        CommodityAuditLogSaveBO logSaveBO = new CommodityAuditLogSaveBO();
        logSaveBO.setAdminId(userId);
        logSaveBO.setShopId(dto.getShopId());//卖家店铺id
        logSaveBO.setAuditStatus(state);//审核状态
        logSaveBO.setCommodityId(dto.getId());//商品id
        logSaveBO.setReturnReason(text);//打回原因
        Wrapper<CommodityAuditLogDTO> wrapper = new EntityWrapper<> ();
        wrapper.eq("commodity_id", dto.getId());
        wrapper.orderBy ("create_time",false);
        List<CommodityAuditLogDTO> commodityAuditLogDTOS = auditLogService.selectList (wrapper);
        if (CustomizeUtil.listIsNotNull (commodityAuditLogDTOS)){
            logSaveBO.setParams (commodityAuditLogDTOS.get (0).getParams ());
        }
        auditLogService.add(logSaveBO);
        return new Result<>();
    }

    @Override
    public HashMap<String, Integer> getVariousCommodity(Long shopId) {
        HashMap<String, Integer> map = new HashMap<>();
        //总数
        Wrapper<CommodityInfoDTO> wrapper = new EntityWrapper<>();
        wrapper.eq("shop_id", shopId);
        wrapper.eq("audit_status", 1);
        wrapper.eq("status", 0);
        Integer total = this.selectCount(wrapper);
        map.put("total", total);
        //已上架
        Wrapper<CommodityInfoDTO> wrapperPublish = new EntityWrapper<>();
        wrapperPublish.eq("shop_id", shopId)
                .eq("is_publish", 1)
                .eq("audit_status", 1)
                .eq("status", 0);
        Integer publishTotal = this.selectCount(wrapperPublish);
        map.put("publishTotal", publishTotal);
        //下架
        Wrapper<CommodityInfoDTO> wrapperNoPush = new EntityWrapper<>();
        wrapperNoPush.eq("shop_id", shopId)
                .eq("audit_status", 1)
                .eq("status", 0)
                .eq("is_publish", 0);
        int noPush = this.selectCount(wrapperNoPush);
        map.put("noPublishTotal", noPush);
        return map;
    }

    @Override
    public List<CommodityInfoRankVO> getCommoditySalesRank(Long shopId) {
        return baseMapper.getCommoditySalesRank(shopId);
    }

    /**
     * @Description: 后台管理系统产品审核列表
     * @Author: WangChenYu
     * @Param: [bo]
     * @Date: 2020-10-10 11:42
     */
    @Override
    public Page<CommodityAuditVO> queryAuditAdminList(CommodityAuditBO bo) {
        Page<CommodityAuditVO> page = new Page<>(bo.getPageNo(), bo.getPageSize());
        List<CommodityAuditVO> list = baseMapper.queryAuditAdminList(page, bo);
        page.setRecords(list);
        return page;
    }

    /**
     * @Description: 平台操作违规删除/下架商品
     * @Author: WangChenYu
     * @Param: [id(商品id), type(0删除，1下架), content(原因)]
     * @Date: 2020-10-10 11:41
     */
    @Override
    public Result<List<String>> updateViolation(Long id, Integer type, String content) {
        Result<List<String>> result = new Result<>();
        CommodityInfoDTO dto = this.selectById(id);
        if (dto == null) {
            result.setCode(CodeEnum.FAIL_COMMODITY_ERROR_340000.getCode());
            result.setMsg(CodeEnum.FAIL_COMMODITY_ERROR_340000.getMsg());
            return result;
        }
        //违规删除
        if (type == ZERO) {
            CommodityInfoDTO updateDto = new CommodityInfoDTO();
            updateDto.setId(dto.getId());
            updateDto.setStatus(ONE);
            updateDto.setIsPlatformShelf(ZERO);
            updateDto.setIsPublish(ZERO);
            updateDto.setIsPlatformRemove(ONE);
            if (StringUtils.isNotBlank(content)) {
                updateDto.setDeleteReason(content);
            }
            boolean update = this.updateById(updateDto);
            if (!update) {
                result.setCode(CodeEnum.FAIL_100009.getCode());
                result.setMsg(CodeEnum.FAIL_100009.getMsg());
                return result;
            }
            //删除商品同事删除新品推荐等
            List<Long> ids = new ArrayList<>();
            ids.add(dto.getId());
            //判断商品是否掌柜推荐 0否、1是
            if (dto.getIsRecommend() == ONE) {
                iEpgShopSectionService.deleteShopSectionBySectionType(ids, dto.getShopId(),
                        ShoppingCodeEnum.SHOPPER_RECOMMEND_3.getMsg());
            }
            // 是否新品上架 0否、1是
            if (dto.getIsNew() == ONE) {
                iEpgShopSectionService.deleteShopSectionBySectionType(ids, dto.getShopId(),
                        ShoppingCodeEnum.NEW_SHOP_1.getMsg());
            }
            // 是否镇店之宝 0否、1是
            if (dto.getIsTreasure() == ONE) {
                iEpgShopSectionService.deleteShopSectionBySectionType(ids, dto.getShopId(),
                        ShoppingCodeEnum.SHOP_BABY_2.getMsg());
            }
            //发送站内信
            String text = "您的商品因为违规,现已被平台删除,请立即查看处理!";
            this.sendMsg(dto.getShopId(), "商品违规删除", text, 0L, 2);
            //从es中删除
            searchService.deleteData("index_goods_2020", "goods", dto.getId().toString());
            result.setCode(CodeEnum.SUCCESS.getCode());
            result.setMsg(CodeEnum.SUCCESS.getMsg());
            return result;
        } else {
            //违规下架
            CommodityInfoDTO updateDto = new CommodityInfoDTO();
            updateDto.setId(dto.getId());
            updateDto.setIsPublish(ZERO);
            updateDto.setIsPlatformShelf(ONE);
            if (StringUtils.isNotBlank(content)) {
                updateDto.setShelfReason(content);
            }
            updateDto.setIsPushLook(0);
            boolean update = this.updateById(updateDto);
            if (!update) {
                result.setCode(CodeEnum.FAIL_100009.getCode());
                result.setMsg(CodeEnum.FAIL_100009.getMsg());
                return result;
            }
            //删除商品同事删除新品推荐等
            List<Long> ids = new ArrayList<>();
            ids.add(dto.getId());
            //判断商品是否掌柜推荐 0否、1是
            if (dto.getIsRecommend() == ONE) {
                iEpgShopSectionService.deleteShopSectionBySectionType(ids, dto.getShopId(),
                        ShoppingCodeEnum.SHOPPER_RECOMMEND_3.getMsg());
            }
            // 是否新品上架 0否、1是
            if (dto.getIsNew() == ONE) {
                iEpgShopSectionService.deleteShopSectionBySectionType(ids, dto.getShopId(),
                        ShoppingCodeEnum.NEW_SHOP_1.getMsg());
            }
            // 是否镇店之宝 0否、1是
            if (dto.getIsTreasure() == ONE) {
                iEpgShopSectionService.deleteShopSectionBySectionType(ids, dto.getShopId(),
                        ShoppingCodeEnum.SHOP_BABY_2.getMsg());
            }
            //发送站内信
            String text = "您的商品因为违规,现已被平台下架,请立即查看处理!";
            this.sendMsg(dto.getShopId(), "商品违规下架", text, 0L, 2);
            // 从es中删除
            searchService.deleteData("index_goods_2020", "goods", dto.getId().toString());
            result.setCode(CodeEnum.SUCCESS.getCode());
            result.setMsg(CodeEnum.SUCCESS.getMsg());
            return result;
        }
    }

    /**
     * @Description: 查询店铺下商品，用于商城店铺装修页
     * @Author: WangChenYu
     * @Param: [bo]
     * @Date: 2020-10-10 11:41
     */
    @Override
    public List<CommodityDecorationVO> queryShopCommodityList(CommodityDecorationBO bo) {
        List<Long> ids = new ArrayList<>();
        if (StringUtils.isNotBlank(bo.getIds())) {
            String[] str = bo.getIds().split(",");
            for (String s : str) {
                ids.add(Long.valueOf(s));
            }
        }
        return baseMapper.queryShopCommodityList(bo, ids);
    }

    /**
     * @Description: 后台管理系统批量审核产品
     * @Author: WangChenYu
     * @Param: [ids, state(1通过，2不通过)]
     * @Date: 2020-10-10 11:40
     */
    @Override
    public Result<List<String>> updateBatchAuditCommodity(String ids, Integer state) {
        Long userId = null;
        Object object = redisUtil.getSession(CommonParameter.getHeadParamsBO ().getSessionId (), CommonParameter.getHeadParamsBO ().getSource ().toString ());
        if(object == null){
            return new Result(CodeEnum.FAIL_100002);
        }
        if(object instanceof UserInfoDTO){
            userId = ((UserInfoDTO) object).getId ();
        } else if(object instanceof SysUserDTO){
            userId = ((SysUserDTO) object).getId ();
        }
        Result<List<String>> result = new Result<>();
        List<CommodityInfoDTO> list = new ArrayList<>();
        String[] split = ids.split(",");
        for (String id : split) {
            CommodityInfoDTO updateDto = new CommodityInfoDTO();
            Long coId = Long.valueOf(id);
            CommodityInfoDTO commodityInfoDTO = baseMapper.selectById (coId);
            if (commodityInfoDTO.getAuditStatus () == 0 || commodityInfoDTO.getAuditStatus () == 4 ){
                if (state == 1){
                    updateDto.setIsPublish(1);
                    //检查店铺资质是否过期
                    Wrapper<ShopQualificationDTO> shopQualificationDTOEntityWrapper = new EntityWrapper<>();
                    shopQualificationDTOEntityWrapper.eq("shop_id",commodityInfoDTO.getShopId());
                    List<ShopQualificationDTO> shopQualificationDTOS = shopQualificationService.selectList(shopQualificationDTOEntityWrapper);
                    if (CustomizeUtil.listIsNotNull(shopQualificationDTOS)){
                        for (ShopQualificationDTO shopQualificationDTO : shopQualificationDTOS) {
                            if (shopQualificationDTO.getExpireStatus()==2) {
                                if (shopQualificationDTO.getType() <= 2) {
                                    updateDto.setIsPublish(0);
                                } else {
                                    if (shopQualificationDTO.getBrandId().equals(commodityInfoDTO.getBrandId())){
                                        updateDto.setIsPublish(0);
                                    }
                                }
                            }
                        }
                    }

                }
                updateDto.setId(coId);
                updateDto.setAuditStatus(state);
                list.add(updateDto);
            }
        }
        if(CustomizeUtil.listIsNotNull (list)){
            boolean update = this.updateBatchById(list);
            if (update) {
                result.setCode(CodeEnum.SUCCESS.getCode());
                result.setMsg(CodeEnum.SUCCESS.getMsg());
                for(CommodityInfoDTO dto : list){
                    //保存审核日志
                    CommodityAuditLogSaveBO logSaveBO = new CommodityAuditLogSaveBO();
                    if (userId != null){
                        logSaveBO.setAdminId(userId);
                    }
                    logSaveBO.setShopId(dto.getShopId());//卖家店铺id
                    logSaveBO.setAuditStatus(state);//审核状态
                    logSaveBO.setCommodityId(dto.getId());//商品id
                    Wrapper<CommodityAuditLogDTO> wrapper = new EntityWrapper<> ();
                    wrapper.eq("commodity_id", dto.getId());
                    wrapper.orderBy ("create_time",false);
                    List<CommodityAuditLogDTO> commodityAuditLogDTOS = auditLogService.selectList (wrapper);
                    if (CustomizeUtil.listIsNotNull (commodityAuditLogDTOS)){
                        logSaveBO.setParams (commodityAuditLogDTOS.get (0).getParams ());
                    }
                    auditLogService.add(logSaveBO);
                    if (state == 1){
                        CommodityEsVO goods = baseMapper.queryESGoodsById(dto.getId());
                        List<EsGoodsDTO> esGoods = this.getEsGoods(goods);
                        searchService.addGoods("index_goods_2020", "goods", 0, esGoods.size(), esGoods);
                    }
                }
            } else {
                result.setCode(CodeEnum.FAIL_COMMODITY_ERROR_340009.getCode());
                result.setMsg(CodeEnum.FAIL_COMMODITY_ERROR_340009.getMsg());
            }
        }else {
            result.setCode(CodeEnum.FAIL_COMMODITY_ERROR_340009.getCode());
            result.setMsg(CodeEnum.FAIL_COMMODITY_ERROR_340009.getMsg());
        }
        return result;
    }

    /**
     * @Description: 查询商城店铺所有商品
     * @Author: WangChenYu
     * @Param: [bo]
     * @Date: 2020-10-10 11:38
     */
    @Override
    public Page<CommodityDecorationVO> queryShopAllCommodityList(CommodityShopAllListBO bo) {
        Page<CommodityDecorationVO> page = new Page<>(bo.getPageNo(), bo.getPageSize());
        List<CommodityDecorationVO> list = baseMapper.queryShopAllCommodityList(page, bo);
        page.setRecords(list);
        return page;
    }

    /**
     * @Description: 后台管理系统店铺所有产品列表
     * @Author: WangChenYu
     * @Param: [bo]
     * @Date: 2020-10-10 11:38
     */
    @Override
    public Page<CommodityAdminShopListVO> queryAdminShopCommodityList(CommodityAdminShopListBO bo) {
        Page<CommodityAdminShopListVO> page = new Page<>(bo.getPageNo(), bo.getPageSize());
        List<CommodityAdminShopListVO> list = baseMapper.queryAdminShopCommodityList(page, bo);
        page.setRecords(list);
        return page;
    }

    /**
     * @Description: 查询所有上架中的产品，用于平台频道装修页
     * @Author: WangChenYu
     * @Param: [bo]
     * @Date: 2020-10-10 11:37
     */
    @Override
    public List<CommodityDecorationVO> queryDecorationCommodityList(CommodityDecorationBO bo) {
        return baseMapper.queryDecorationCommodityList(bo);
    }

    /**
     * @Description: 商城商品详情页
     * @Author: WangChenYu
     * @Param: [id]
     * @Date: 2020-10-10 11:37
     */
    @Override
    public CommodityDetailsPageVO queryCommodityDetailsPageData(Long id) {
        CommodityDetailsPageVO vo = commodityDetailsPageMapper.queryCommodityDetailsPageData(id);
        if (null == vo) {
            return null;
        }
        if (vo.getSendAreaId() != null) {
            String names = "";
            vo.setSendAreaName(this.packageShippingArea(vo.getSendAreaId(), names));
        }
//        //获取商品规格属性
//        List<SpecificationCategoryVO> specificationCategory = commodityDetailsPageMapper.getSpecificationCategory(vo.getCategoryId(), vo.getBrandId());
//        if (!isNull(specificationCategory)) {
//            vo.setCategorySpecInformation(specificationCategory);
//        }
        // 获取商品已录入的规格属性
        List<SpecificationCategoryVO> goodsAllAttrs = this.getGoodsAllAttrs(id);
        if (null != goodsAllAttrs && goodsAllAttrs.size() > 0) {
            vo.setCategorySpecInformation(goodsAllAttrs);
        }
        //判断店铺是否冻结
        boolean checkShopIsClose = shopInfoService.checkShopIsClose(vo.getShopId());
        if (checkShopIsClose) {
            vo.setShopIsClose(0);//正常
        } else {
            vo.setShopIsClose(1);//冻结
        }
        ShopInfoDTO shopInfoDTO = shopInfoService.selectById(vo.getShopId());
        if (shopInfoDTO!=null){
            vo.setDomain(shopInfoDTO.getDomain());
        }
        return vo;
    }

//    /**
//     * @Description: 获取商品信息，用于es
//     * @Author: WangChenYu
//     * @Param: []
//     * @Date: 2020-10-10 11:37
//     */
//    @Override
//    public List<CommodityEsVO> queryESGoods() {
//        List<CommodityEsVO> list = baseMapper.queryESGoods();
//        for (CommodityEsVO commodityEsVO : list) {
//            commodityEsVO.setPayUserNum(baseMapper.queryPayUserNum(commodityEsVO.getId()));
//        }
//        if (isNull(list)) {
//            return Collections.EMPTY_LIST;
//        }
//        Iterator<CommodityEsVO> iterator = list.iterator();
//        while (iterator.hasNext()) {
//            boolean checkShopIsClose = shopInfoService.checkShopIsClose(iterator.next().getSellerShopId());
//            if (!checkShopIsClose) {
//                iterator.remove();
//            }
//        }
//        log.info("ES商品搜索查询 : {}", list);
//        return list;
//    }

    /**
     * @Description: 最新获取商品信息，用于es
     * @Author: WangChenYu
     * @Param: []
     * @Date: 2020-10-10 11:37
     */
    @Override
    public List<CommodityEsVO> queryAllESGoods(long offset) {
        List<CommodityEsVO> list = baseMapper.queryAllESGoods(offset);
        if (isNull(list)) {
            return Collections.EMPTY_LIST;
        }
        log.info("ES商品搜索查询 : {}", list);
        return list;
    }

    /**
     * @Description: 最新获取商品信息，用于es
     * @Author: WangChenYu
     * @Param: []
     * @Date: 2020-10-10 11:37
     */
    @Override
    public List<CommodityEsVO> queryAllESGoodsByCommodityId(long id) {
        List<CommodityEsVO> list = baseMapper.queryAllESGoodsByCommodityId(id);
        if (isNull(list)) {
            return Collections.EMPTY_LIST;
        }
        log.info("ES商品搜索查询 : {}", list);
        return list;
    }

    @Override
    public int queryAllESGoodsCount() {
        return baseMapper.queryAllESGoodsCount();
    }

    @Override
    public CommodityExportVO queryGoodsByIds(Long id) {
        return baseMapper.queryGoodsByIds(id);
    }

    /*
     * @description:获取商品所拥有的规格属性
     * @author: chenyu.wang
     * @date: 2020-09-08
     */
    @Override
    public List<SpecificationCategoryVO> getGoodsAllAttrs(Long id) {
        List<SpecificationCategoryVO> list = commodityDetailsPageMapper.queryGoodsAttrs(id);
        if (isNull(list)) {
            return null;
        }
        for (SpecificationCategoryVO vo : list) {
            List<CommodityAttrVO> attrVOS = commodityDetailsPageMapper.queryGoodsAttrBySpecificationId(vo.getSpecificationId(), id);
            if (!isNull(attrVOS)) {
                vo.setAttrList(attrVOS);
            }
        }
        return list;
    }

    @Override
    public List<CommoditySKUVO> getGoodsSku(Long id) {
        List<CommoditySKUVO> objects = new ArrayList<>();
        Wrapper<CommoditySpecificationRelationDTO> wrapper = new EntityWrapper<>();
        wrapper.eq("commodity_id", id);
        List<CommoditySpecificationRelationDTO> list = commoditySpecificationRelationService.selectList(wrapper);
        if (isNull(list)) {
            return null;
        }
        for (CommoditySpecificationRelationDTO relationDTO : list) {
            CommoditySKUVO skuvo = new CommoditySKUVO();
            String ids = relationDTO.getAttrIds();
            String[] split = ids.split(",");
            List<Long> longList = new ArrayList<>();
            for (String s : split) {
                longList.add(Long.valueOf(s));
            }
            skuvo.setList(longList);
            objects.add(skuvo);
        }
        return objects;
    }

    /*
     * @description:同一类目下的商品价格比较
     * @author: chenyu.wang
     * @date: 2020-09-15
     * @return:
     */
    @Override
    public String getGoodsCompare(Long categoryId) {
        //查询类目下已上架的商品
        Wrapper<CommodityInfoDTO> wrapper = new EntityWrapper<>();
        wrapper.eq("category_id", categoryId);
        wrapper.eq("is_publish", ONE);
        wrapper.eq("status", ZERO);
        wrapper.eq("is_Inquiry", ZERO);
        List<CommodityInfoDTO> list = this.selectList(wrapper);
        if (isNull(list)) {
            return null;
        }
        List<BigDecimal> quiteVOList = new ArrayList<>();
        for (CommodityInfoDTO dto : list) {
            // 查询规格最高最低价格
            CommodityPriceCheckVO price = baseMapper.getGoodsPrice(dto.getId());
            // 查询套餐最高最低价格
            CommodityPriceCheckVO comboPrice = baseMapper.getGoodsComboPrice(dto.getId());
            if (null != price) {
                quiteVOList.add(price.getMaxPrice());
                quiteVOList.add(price.getMinPrice());
            }
            if (null != comboPrice) {
                quiteVOList.add(comboPrice.getMaxPrice());
                quiteVOList.add(comboPrice.getMinPrice());
            }
        }
        if (isNull(quiteVOList)) {
            return null;
        }
        BigDecimal min = Collections.min(quiteVOList);
        BigDecimal max = Collections.max(quiteVOList);
        String minPrice = min.setScale(2, BigDecimal.ROUND_HALF_UP).toString();
        String maxPrice = max.setScale(2, BigDecimal.ROUND_HALF_UP).toString();
        return minPrice + "-" + maxPrice;
    }

    @Override
    public CommodityAdminExportVO queryAdminExportGoods(Long goodsId) {
        return baseMapper.queryAdminExportGoods(goodsId);
    }

    /*
     * @description:批量彻底删除商品
     * @author: chenyu.wang
     * @date: 2020-09-23
     * @return:
     */
    @Override
    public Result<List<String>> deleteBatchPhysical(String ids) {
        Result<List<String>> result = new Result<>();
        List<CommodityInfoDTO> list = new ArrayList<>();
        String[] idList = ids.split(",");
        CommodityInfoDTO dto = this.selectById(idList[0]);
        //判断店铺是否冻结
        boolean checkShopIsClose = shopInfoService.checkShopIsClose(dto.getShopId());
        if (!checkShopIsClose) {
            result.setCode(CodeEnum.FAIL_COMMODITY_ERROR_340015.getCode());
            result.setMsg(CodeEnum.FAIL_COMMODITY_ERROR_340015.getMsg());
            return result;
        }
        for (String id : idList) {
            CommodityInfoDTO updateDTO = new CommodityInfoDTO();
            updateDTO.setId(Long.valueOf(id));
            updateDTO.setIsRemove(ONE);
            list.add(updateDTO);
        }
        boolean updateBatchById = this.updateBatchById(list);
        if (updateBatchById) {
            result.setCode(CodeEnum.SUCCESS.getCode());
            result.setMsg(CodeEnum.SUCCESS.getMsg());
            return result;
        } else {
            result.setCode(CodeEnum.FAIL_100009.getCode());
            result.setMsg(CodeEnum.FAIL_100009.getMsg());
            return result;
        }
    }

    /**
     * @Description: 根据店铺id批量下架产品, 权限为admin, 不能再次上架
     * @Author: WangChenYu
     * @Param: [shopId]
     * @Date: 2020-10-09 16:04
     */
    @Async
    @Override
    public void updateStateByShopId(Long shopId) {
        Wrapper<CommodityInfoDTO> wrapper = new EntityWrapper<>();
        wrapper.eq("shop_id", shopId);
        List<CommodityInfoDTO> list = this.selectList(wrapper);
        if (!isNull(list)) {
            for (CommodityInfoDTO dto : list) {
                CommodityInfoDTO updateDTO = new CommodityInfoDTO();
                updateDTO.setId(dto.getId());
                updateDTO.setIsPublish(ZERO);
                updateDTO.setIsPlatformShelf(ONE);
                updateDTO.setShelfReason("店铺关店");
                this.updateById(updateDTO);
            }
        }
    }

    /**
     * @Description: 后台管理系统产品回收站
     * @Author: WangChenYu
     * @Param: [pageNo, pageSize]
     * @Date: 2020-10-10 10:50
     */
    @Override
    public Page<CommodityAdminListVO> queryAdminGoodsRecycleBin(CommodityAdminListBO bo) {
        Page<CommodityAdminListVO> page = new Page<>(bo.getPageNo(), bo.getPageSize());
        List<CommodityAdminListVO> list = baseMapper.queryAdminGoodsRecycleBin(page, bo);
        if (!isNull(list)) {
            for (CommodityAdminListVO vo : list) {
                String goodsCategoryName = commodityCategoryService.creatTreeById(vo.getCategoryId(), "");
                if (StringUtils.isNotBlank(goodsCategoryName)) {
                    vo.setGoodsCategoty(goodsCategoryName);
                }
            }
        }
        page.setRecords(list);
        return page;
    }

    @Override
    public void updateBackInventory(Long goodsId, String ids, Integer num) {
        // 先将规格ids排序
        String ids1 = getIds(ids);
        // 先查询规格
        CommodityAttrPriceVO sku = commoditySpecificationRelationService.getGoodsSkuPrice(goodsId, ids1);
        if (null != sku) {
            CommoditySpecificationRelationDTO updateDto = new CommoditySpecificationRelationDTO();
            updateDto.setId(sku.getId());
            updateDto.setInventoryNumber(num);
            commoditySpecificationRelationService.updateById(updateDto);
            return;
        }
        // 再查询套餐
        CommodityComboRelationVO comboRelationVO = commodityComboRelationService.getByGoodsIdAndComboId(goodsId, Long.valueOf(ids1));
        if (null != comboRelationVO) {
            CommodityComboRelationDTO comboRelationDTO = new CommodityComboRelationDTO();
            comboRelationDTO.setId(comboRelationVO.getId());
            comboRelationDTO.setInventoryNumber(num);
            commodityComboRelationService.updateById(comboRelationDTO);
        }
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public Result updateGoodsBack(CommodityReleaseBO bo) {
        Result<Object> result = new Result<>();
        Long goodsId = bo.getId();
        //判断店铺是否冻结
        boolean checkShopIsClose = shopInfoService.checkShopIsClose(bo.getShopId());
        if (!checkShopIsClose) {
            result.setCode(CodeEnum.FAIL_COMMODITY_ERROR_340015.getCode());
            result.setMsg(CodeEnum.FAIL_COMMODITY_ERROR_340015.getMsg());
            return result;
        }

        //检查店铺资质是否过期
        Wrapper<ShopQualificationDTO> shopQualificationDTOEntityWrapper = new EntityWrapper<>();
        shopQualificationDTOEntityWrapper.eq("shop_id",bo.getShopId());
        List<ShopQualificationDTO> shopQualificationDTOS = shopQualificationService.selectList(shopQualificationDTOEntityWrapper);
        if (CustomizeUtil.listIsNotNull(shopQualificationDTOS)){
            for (ShopQualificationDTO dto : shopQualificationDTOS) {
                if (dto.getExpireStatus()==2) {
                    if (dto.getType() <= 2) {
                        result.setCode(CodeEnum.FAIL_SHOP_BASIC_CERTIFICATION_EXPIRE_3011.getCode());
                        result.setMsg(CodeEnum.FAIL_SHOP_BASIC_CERTIFICATION_EXPIRE_3011.getMsg());
                        return result;
                    } else {
                        if (bo.getBrandId().equals(dto.getBrandId())){
                            if (dto.getType()==3){
                                for (ShopQualificationDTO shopQualificationDTO : shopQualificationDTOS) {
                                    if (shopQualificationDTO.getType()==4 && shopQualificationDTO.getExpireStatus()==2){
                                        result.setCode(CodeEnum.FAIL_COMMODITY_ERROR_340013.getCode());
                                        result.setMsg(CodeEnum.FAIL_COMMODITY_ERROR_340013.getMsg());
                                        return result;
                                    }
                                }
                            }else {
                                result.setCode(CodeEnum.FAIL_COMMODITY_ERROR_340013.getCode());
                                result.setMsg(CodeEnum.FAIL_COMMODITY_ERROR_340013.getMsg());
                                return result;
                            }
                        }
                    }
                }
            }
        }

        CommodityInfoDTO commodityInfoDTO = new CommodityInfoDTO();
        commodityInfoDTO.setLogoUrl(bo.getLogoUrl());
        commodityInfoDTO.setLogoUrls(bo.getLogoUrls());
        commodityInfoDTO.setVideoUrls(bo.getVideoUrls());
        commodityInfoDTO.setName(bo.getName());
        commodityInfoDTO.setDescription(bo.getDescription());
        commodityInfoDTO.setSendAreaId(bo.getSendAreaId());
        commodityInfoDTO.setAvailableArea(bo.getAvailableArea());
        commodityInfoDTO.setSendDays(bo.getSendDays());
        if (null != bo.getType()) {
            commodityInfoDTO.setType(bo.getType());
            if (bo.getType() != 1) {
                commodityInfoDTO.setPayType(ZERO);//全额
            } else {
                commodityInfoDTO.setPayType(ONE);//分期
            }
        }
        commodityInfoDTO.setShopId(bo.getShopId());
        commodityInfoDTO.setBrandId(bo.getBrandId());
        commodityInfoDTO.setCategoryId(bo.getCategoryId());
        commodityInfoDTO.setNotes(bo.getNotes());
        commodityInfoDTO.setAuditStatus(4);
        commodityInfoDTO.setIsPublish(0);
        commodityInfoDTO.setStatus(0);
        commodityInfoDTO.setIsRecommend(bo.getIsRecommend());
        commodityInfoDTO.setIsNew(bo.getIsNew());
        commodityInfoDTO.setIsTreasure(bo.getIsTreasure());
        commodityInfoDTO.setWarrantyMonth(bo.getWarrantyMonth());
        commodityInfoDTO.setProductSpecificationUrl(bo.getProductSpecificationUrl());
        commodityInfoDTO.setCommodityNumber(bo.getCommodityNumber());
        commodityInfoDTO.setProductCertificateUrls(bo.getProductCertificateUrls());
        commodityInfoDTO.setIsVipDiscounts(bo.getIsVipDiscounts());
        commodityInfoDTO.setFirstBalance(bo.getFirstBalance());
        commodityInfoDTO.setTailBalance(bo.getTailBalance());
        commodityInfoDTO.setIsInquiry(bo.getIsInquiry());
        commodityInfoDTO.setSellerAddressId(bo.getSellerAddressId());
        commodityInfoDTO.setIsPlatformShelf(0);
        commodityInfoDTO.setFilterIds(bo.getFilterIds());
        commodityInfoDTO.setIsRemove(0);
        commodityInfoDTO.setIsPlatformRemove(0);
        commodityInfoDTO.setId(goodsId);
        if (bo.getStockDays() != null) {
            commodityInfoDTO.setStockDays(bo.getStockDays());
        }
        boolean update = this.updateById(commodityInfoDTO);
        if (!update) {
            result.setCode(CodeEnum.FAIL_COMMODITY_ERROR_340006.getCode());
            result.setMsg(CodeEnum.FAIL_COMMODITY_ERROR_340006.getMsg());
            return result;
        }
        // 保存商品规格信息
        if (StringUtils.isNotBlank(bo.getAttrs())) {
            Wrapper<CommoditySpecificationRelationDTO> wrapper = new EntityWrapper<>();
            wrapper.eq("commodity_id", goodsId);
            List<CommoditySpecificationRelationDTO> list = commoditySpecificationRelationService.selectList(wrapper);
            if (!isNull(list)) {
                commoditySpecificationRelationService.delete(wrapper);
            }
            this.saveGoodsAttrs(bo.getAttrs(), goodsId);
        }
        // 商品套餐信息
        if (StringUtils.isNotBlank(bo.getCombos())) {
            Wrapper<CommodityComboRelationDTO> wrapper = new EntityWrapper<>();
            wrapper.eq("commodity_id", goodsId);
            List<CommodityComboRelationDTO> list = commodityComboRelationService.selectList(wrapper);
            if (!isNull(list)) {
                commodityComboRelationService.delete(wrapper);
            }
            this.saveGoodsCombo(bo.getCombos(), goodsId);
        }
        // 商品参数信息
        if (StringUtils.isNotBlank(bo.getParamValues())) {
            Wrapper<CommodityParamValueRelationDTO> wrapper = new EntityWrapper<>();
            wrapper.eq("commodity_id", goodsId);
            List<CommodityParamValueRelationDTO> list = commodityParamValueRelationService.selectList(wrapper);
            if (!isNull(list)) {
                commodityParamValueRelationService.delete(wrapper);
            }
            this.saveParamValue(bo.getParamValues(), goodsId);
        }
        // 商品销售信息
        if (StringUtils.isNotBlank(bo.getSalesAttributes())) {
            Wrapper<CommoditySalesAttributesRelationDTO> wrapper = new EntityWrapper<>();
            wrapper.eq("commodity_id", goodsId);
            List<CommoditySalesAttributesRelationDTO> list = commoditySalesAttributesRelationService.selectList(wrapper);
            if (!isNull(list)) {
                commoditySalesAttributesRelationService.delete(wrapper);
            }
            this.saveSalesAttributes(bo.getSalesAttributes(), goodsId);
        }
        //保存审核日志
        CommodityAuditLogSaveBO logSaveBO = new CommodityAuditLogSaveBO();
        ShopInfoDTO shopInfoDTO = shopInfoService.selectById (bo.getShopId ());
        if (shopInfoDTO != null){
            logSaveBO.setAdminId(shopInfoDTO.getUserId ());
        }
        logSaveBO.setShopId(bo.getShopId());//卖家店铺id
        logSaveBO.setAuditStatus(4);//审核状态
        logSaveBO.setCommodityId(commodityInfoDTO.getId());//商品id
//        String params = JSON.toJSONString (bo);
//        log.info ("bo--JSON---1" + params);
//        logSaveBO.setParams (params);
        auditLogService.add(logSaveBO);

        result.setCode(CodeEnum.SUCCESS.getCode());
        result.setMsg(CodeEnum.SUCCESS.getMsg());

        return result;
    }

    @Override
    public CommodityEsVO queryESGoodsById(Long goodsId) {
        return baseMapper.queryESGoodsById(goodsId);
    }

    /**
     * @Description: 修改商品规格属性
     * @Author: WangChenYu
     * @Param: [attrs, goodsId]
     * @Date: 2020-10-10 15:13
     */
    private void updateGoodsAttrs(String attrs, Long goodsId) {
        log.info("规格属性 : {},商品id : {}", attrs, goodsId);
        List<CommoditySpecificationRelationDTO> list = new ArrayList<>();
        List<CommoditySpecificationRelationSaveBO> ids = JSONObject.parseArray(attrs, CommoditySpecificationRelationSaveBO.class);
        if (ids != null && ids.size() > 0) {
            for (CommoditySpecificationRelationSaveBO saveBO : ids) {
                CommoditySpecificationRelationDTO dto = new CommoditySpecificationRelationDTO();
                //规格属性ids排序
                String skuIds = getIds(saveBO.getAttrIds());
                dto.setId(saveBO.getId());
                dto.setCommodityId(goodsId);
                dto.setAttrIds(skuIds);
                if (saveBO.getPrice() != null) {
                    dto.setPrice(saveBO.getPrice());
                }
                if (saveBO.getWholesalePrice() != null) {
                    dto.setWholesalePrice(saveBO.getWholesalePrice());
                }
                if (saveBO.getOriginalPrice() != null) {
                    dto.setOriginalPrice(saveBO.getOriginalPrice());
                }
                dto.setInventoryNumber(saveBO.getInventoryNumber());
                dto.setCommoditySize(saveBO.getCommoditySize());
                dto.setCommoditySizeUnit(saveBO.getCommoditySizeUnit());
                dto.setCommodityUnit(saveBO.getCommodityUnit());
                dto.setInventoryNumberWarning(saveBO.getInventoryNumberWarning());
                if (saveBO.getBatchNumber() != null) {
                    dto.setBatchNumber(saveBO.getBatchNumber());
                }
                dto.setAtrrNames(saveBO.getAtrrNames());
                list.add(dto);
                //将商品库存放入reids
                redisUtil.saveCommodityNum(goodsId, skuIds, saveBO.getInventoryNumber());
            }
            //保存商品规格信息
            commoditySpecificationRelationService.updateBatchById(list);
        }
    }

    /**
     * @Description: 修改商品套餐信息
     * @Author: WangChenYu
     * @Param: [combos, goodsId]
     * @Date: 2020-10-10 15:13
     */
    private void updateGoodsCombo(String combos, Long goodsId) {
        log.info("套餐信息 : {},商品id : {}", combos, goodsId);
        List<CommodityComboRelationDTO> list = new ArrayList<>();
        List<CommodityComboRelationSaveBO> comboList = JSONObject.parseArray(combos, CommodityComboRelationSaveBO.class);
        if (comboList != null && comboList.size() > 0) {
            for (CommodityComboRelationSaveBO relationSaveBO : comboList) {
                CommodityComboRelationDTO dto = new CommodityComboRelationDTO();
                dto.setId(relationSaveBO.getId());
                dto.setCommodityId(goodsId);
                dto.setComboName(relationSaveBO.getComboName());
                if (relationSaveBO.getPrice() != null) {
                    dto.setPrice(relationSaveBO.getPrice());
                }
                if (relationSaveBO.getWholesalePrice() != null) {
                    dto.setWholesalePrice(relationSaveBO.getWholesalePrice());
                }
                if (relationSaveBO.getOriginalPrice() != null) {
                    dto.setOriginalPrice(relationSaveBO.getOriginalPrice());
                }
                dto.setInventoryNumber(relationSaveBO.getInventoryNumber());
                dto.setCommoditySize(relationSaveBO.getCommoditySize());
                dto.setCommoditySizeUnit(relationSaveBO.getCommoditySizeUnit());
                dto.setCommodityUnit(relationSaveBO.getCommodityUnit());
                dto.setInventoryNumberWarning(relationSaveBO.getInventoryNumberWarning());
                if (relationSaveBO.getBatchNumber() != null) {
                    dto.setBatchNumber(relationSaveBO.getBatchNumber());
                }
                list.add(dto);
                //将商品库存放入reids
                redisUtil.saveCommodityNum(goodsId, relationSaveBO.getId().toString(), relationSaveBO.getInventoryNumber());
            }
            //保存商品套餐信息
            commodityComboRelationService.updateBatchById(list);
        }
    }

    /**
     * @Description: 封装发货区域名称
     * @Author: WangChenYu
     * @Param: [id, names]
     * @Date: 2020-10-10 15:13
     */
    public String packageShippingArea(Long id, String names) {
        SysAreaDTO dto = baseMapper.queryAreaInformation(id);
        if (dto == null) {
            return "";
        }
        if (dto.getParentId() == ZERO) {
            SysAreaDTO areaDTO = baseMapper.queryAreaInformation(id);
            StringBuilder stringBuffer = new StringBuilder(names);
            stringBuffer.insert(0, areaDTO.getName());
            return stringBuffer.toString();
        } else {
            StringBuilder stringBuffer = new StringBuilder(names);
            stringBuffer.insert(0, dto.getName());
            return this.packageShippingArea(dto.getParentId(), stringBuffer.toString());
        }
    }

    /**
     * @description: 发送站内信
     * @author: chenyu.wang
     * @date: 2020-09-30
     * @return:
     */
    @Async
    public void sendMsg(Long shopId, String title, String content, Long orderId, Integer shopType) {
        try {
            ResponseDTO responseDTO = new ResponseDTO();
            responseDTO.setMessageId(shopId + "");
            MessageAnnouncementSaveBO messageAnnouncementSaveBO = new MessageAnnouncementSaveBO();
            messageAnnouncementSaveBO.setType(MessageEnum.SYS_MESSAGE.getCode());
            messageAnnouncementSaveBO.setShopId(shopId);
            messageAnnouncementSaveBO.setTitle(title);
            messageAnnouncementSaveBO.setContent(content);
            messageAnnouncementSaveBO.setTextType(1);
            messageAnnouncementSaveBO.setJumpType(MessageEnum.MESSAGE_SHOW.getCode() + "");
            if (shopType == ONE) {//买家
                messageAnnouncementSaveBO.setShopType(MessageEnum.SHOP_TYPE_1.getCode());
            } else if (shopType == 2) {//卖家
                messageAnnouncementSaveBO.setShopType(MessageEnum.SHOP_TYPE_2.getCode());
            } else {
                messageAnnouncementSaveBO.setShopType(shopType);
            }
            messageAnnouncementSaveBO.setKey(orderId + "");
            responseDTO.setData(messageAnnouncementSaveBO);
            //暂时停用2023-08-25
            //iKafkaProducerService.senMessage(JSON.toJSONString(responseDTO), MessageTopicType.COMMENT_MESSAGE_TOPIC);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * @Description: 根据最低级类目获取最高级类目Id
     * @Author: WangChenYu
     * @Param: [categoryId]
     * @Date: 2020-10-09 15:45
     */
    private CommodityCategoryDTO getTopCategory(Long categoryId) {
        CommodityCategoryDTO dto = commodityCategoryService.selectById(categoryId);
        if (dto == null) {
            return null;
        }
        if (dto.getParentId() == ZERO) {
            return dto;
        }
        return this.getTopCategory(dto.getParentId());
    }

    /**
     * @Description: 修改商品参数信息
     * @Author: chenyu.wang
     * @Params: [values, goodsId]
     * @Date: 2020.11.03 15:45
     */
    private void updateParamValue(String values, Long goodsId) {
        // 先删除，再新增
        Wrapper<CommodityParamValueRelationDTO> wrapper = new EntityWrapper<>();
        wrapper.eq("commodity_id", goodsId);
        commodityParamValueRelationService.delete(wrapper);
        List<CommodityParamValueRelationSaveBO> saveList = JSON.parseArray(values, CommodityParamValueRelationSaveBO.class);
        if (!isNull(saveList)) {
            for (CommodityParamValueRelationSaveBO bo : saveList) {
                CommodityParamValueRelationDTO dto = new CommodityParamValueRelationDTO();
                dto.setId(ymlConfig.getPkId());
                dto.setCommodityId(goodsId);
                dto.setParamId(bo.getParamId());
                dto.setParamValueIds(bo.getParamValueIds());
                commodityParamValueRelationService.insert(dto);
            }
        }
    }

    /**
     * @Description: 获取商品
     * @Author: chenyu.wang
     * @Params: [vo]
     * @Date: 2020.11.18 11:54
     */
    @Override
    public List<EsGoodsDTO> getEsGoods(CommodityEsVO vo) {
        List<EsGoodsDTO> goodsList = new ArrayList<>();
        EsGoodsDTO goodsDTO = new EsGoodsDTO();
        goodsDTO.setId(vo.getId());
        goodsDTO.setLogUrl(vo.getLogUrl());
        goodsDTO.setGoodsName(vo.getGoodsName());
        goodsDTO.setGoodsNameIkSmart(vo.getGoodsName());
        goodsDTO.setGoodsNameIkMaxWord(vo.getGoodsName());
        goodsDTO.setDescription(vo.getDescription());
        goodsDTO.setPrice(vo.getPrice().doubleValue());
        goodsDTO.setOriginalPrice(vo.getOriginalPrice().doubleValue());
        goodsDTO.setPayUserNum(vo.getPayUserNum());
        goodsDTO.setSellerShopId(vo.getSellerShopId());
        goodsDTO.setSellerShopName(vo.getSellerShopName());
        goodsDTO.setSellerShopAddress(vo.getSellerShopAddress());
        goodsDTO.setBrandId(vo.getBrandId().toString());
        goodsDTO.setBrandName(vo.getBrandName());
        goodsDTO.setBrandNameIkSmart(vo.getBrandName());
        goodsDTO.setBrandNameIkMaxWord(vo.getBrandName());
        goodsDTO.setCategoryId(vo.getCategoryId());
        goodsDTO.setCategoryName(vo.getCategoryName());
        goodsDTO.setIsNew(vo.getIsNew());
        goodsDTO.setPopularity(vo.getPopularity());
        goodsDTO.setEvaluationNum(vo.getEvaluationNum());
        goodsDTO.setCreateTime(vo.getCreateTime());
        goodsDTO.setParentCategoryId(vo.getParentCategoryId());
        goodsDTO.setFirstCategoryId(vo.getFirstCategoryId());
        goodsDTO.setFilterIds(vo.getFilterIds());
        goodsDTO.setFilterNames(vo.getFilterNames());
        if (StringUtils.isNotBlank(vo.getFilterNames())) {
            String[] split = vo.getFilterNames().split(",");
            goodsDTO.setFilterName(split);
        }
        goodsDTO.setIsXun(vo.getIsXun());
        goodsDTO.setBrowseAmount(vo.getBrowseAmount());
        goodsList.add(goodsDTO);
        return goodsList;
    }

    @Override
    public List<CommodityExportVO> queryAllGoodsSku(Long id) {
        // 查询商品
        CommodityInfoDTO select = this.selectById(id);
        if (select == null) {
            return null;
        }
        List<CommodityExportVO> result = new ArrayList<>();
        // 查询商品规格型号
        Wrapper<CommoditySpecificationRelationDTO> wrapper = new EntityWrapper<>();
        wrapper.eq("commodity_id", select.getId());
        List<CommoditySpecificationRelationDTO> list = commoditySpecificationRelationService.selectList(wrapper);
        if (!isNull(list)) {
            for (CommoditySpecificationRelationDTO dto : list) {
                CommodityExportVO vo = new CommodityExportVO();
                vo.setGoodsNum(select.getCommodityNumber());
                vo.setGoodsName(select.getName());
                vo.setSpecificationName(dto.getAtrrNames());
                vo.setGoodsPrice(dto.getPrice());
                result.add(vo);
            }
        }
        // 查询套餐
        Wrapper<CommodityComboRelationDTO> wrapperA = new EntityWrapper<>();
        wrapperA.eq("commodity_id", select.getId());
        List<CommodityComboRelationDTO> listA = commodityComboRelationService.selectList(wrapperA);
        if (!isNull(listA)) {
            for (CommodityComboRelationDTO dto : listA) {
                CommodityExportVO vo = new CommodityExportVO();
                vo.setGoodsNum(select.getCommodityNumber());
                vo.setGoodsName(select.getName());
                vo.setSpecificationName(dto.getComboName());
                vo.setGoodsPrice(dto.getPrice());
                result.add(vo);
            }
        }
        return result;
    }

    @Override
    public List<CommodityAdminExportVO> getAdminExportGoods(Long id) {
        CommodityInfoDTO select = this.selectById(id);
        if (select == null) {
            return null;
        }
        List<CommodityAdminExportVO> result = new ArrayList<>();
        // 查询品牌
        BrandInfoDTO selectB = brandInfoMapper.selectById(select.getBrandId());
        // 查询店铺
        ShopInfoDTO selectC = shopInfoService.selectById(select.getShopId());
        // 查询规格型号
        Wrapper<CommoditySpecificationRelationDTO> wrapper = new EntityWrapper<>();
        wrapper.eq("commodity_id", select.getId());
        List<CommoditySpecificationRelationDTO> list = commoditySpecificationRelationService.selectList(wrapper);
        if (!isNull(list)) {
            for (CommoditySpecificationRelationDTO dto : list) {
                CommodityAdminExportVO exportVO = new CommodityAdminExportVO();
                exportVO.setGoodsName(select.getName());
                exportVO.setAttrName(dto.getAtrrNames());
                if (selectB != null) {
                    exportVO.setBrandName(selectB.getName());
                }
                if (selectC != null) {
                    exportVO.setShopName(selectC.getShopName());
                }
                exportVO.setGoodsPrice(dto.getPrice());
                result.add(exportVO);
            }
        }
        // 查询套餐
        Wrapper<CommodityComboRelationDTO> wrapperB = new EntityWrapper<>();
        wrapperB.eq("commodity_id", select.getId());
        List<CommodityComboRelationDTO> listB = commodityComboRelationService.selectList(wrapperB);
        if (!isNull(listB)) {
            for (CommodityComboRelationDTO dto : listB) {
                CommodityAdminExportVO exportVO = new CommodityAdminExportVO();
                exportVO.setGoodsName(select.getName());
                exportVO.setAttrName(dto.getComboName());
                if (selectB != null) {
                    exportVO.setBrandName(selectB.getName());
                }
                if (selectC != null) {
                    exportVO.setShopName(selectC.getShopName());
                }
                exportVO.setGoodsPrice(dto.getPrice());
                result.add(exportVO);
            }
        }
        return result;
    }

    @Override
    public void doImageUrlWM() {
        List<CommodityInfoDTO> list = this.selectList(new EntityWrapper<>());
        if (list != null && list.size() > 0) {
            for (CommodityInfoDTO dto : list) {
                try {
                    String htmlStr = dto.getNotes();
                    List<String> imgSrcList = UeditorUtils.getImgStr(htmlStr);
                    if (imgSrcList != null && imgSrcList.size() > 0) {
                        for (String imgSrc : imgSrcList) {
                            System.out.println("----imgSrc-----" + imgSrc + "------" + dto.getId());
                            if (StrUtils.isNotEmpty(imgSrc) && !imgSrc.toLowerCase().startsWith("http")) {
                                String fileName = FileUtils.getFileName(imgSrc);
                                String fileExtName = FileUtils.getFileExtName(imgSrc);
                                if (!fileName.toLowerCase().endsWith("wm")) {
                                    String imgSrcWm = fileName + "wm." + fileExtName;
                                    htmlStr = htmlStr.replaceAll(imgSrc, imgSrcWm);
                                }

                            }
                        }

                    }
                    String imgSrcs = dto.getLogoUrls();
                    if (StrUtils.isNotEmpty(imgSrcs)) {
                        String[] srcs = imgSrcs.split(",");
                        String urls = "";
                        for (String src : srcs) {
                            System.out.println("----imgSrc-----" + srcs + "------" + dto.getId());
                            String fileName = FileUtils.getFileName(src);
                            String fileExtName = FileUtils.getFileExtName(src);
                            if (!fileName.toLowerCase().endsWith("wm")) {
                                String imgSrcWm = fileName + "wm." + fileExtName;
                                urls += imgSrcWm + ",";
                            }
                        }
                        if (urls.length() > 0) {
                            urls = urls.substring(0, urls.length() - 1);
                            dto.setLogoUrls(urls);
                        }
                    }
                    dto.setNotes(htmlStr);
                    updateById(dto);
                } catch (Exception e) {
                    e.printStackTrace();
                    log.info("--------" + dto.getId() + "-----" + dto.getName());
                }

            }
        }
    }

    @Override
    public void updateLogImg() {
        // 查询商品
        Wrapper<CommodityInfoDTO> wrapper = new EntityWrapper<>();
        List<CommodityInfoDTO> list = this.selectList(wrapper);
        if (CustomizeUtil.listIsNull(list)) {
            return;
        }
        for (CommodityInfoDTO infoDTO : list) {
            if (CustomizeUtil.strIsNull(infoDTO.getLogoUrl())) {
                continue;
            }
            List<String> asList = new ArrayList<>();
            String logoUrl = infoDTO.getLogoUrl();
            // 长度
            int length = logoUrl.length();
            // 截取长度
            int b = length - 4;
            // 后缀
            String suffix = logoUrl.substring(b);
            // 前面需要拼接的部分
            String front = logoUrl.substring(0, b);
            // 增加wm
            String newFront = front + "wm";
            // 新的地址
            String newLogUrl = newFront + suffix;
            log.info("新的商品主图:{}", newLogUrl);
            asList.add(newLogUrl);
            if (CustomizeUtil.strIsNotNull(infoDTO.getLogoUrls())) {
                String[] split = infoDTO.getLogoUrls().split(",");
                for (String s : split) {
                    log.info("s:{}", s);
                    asList.add(s);
                }
            }
            CommodityInfoDTO updateDto = new CommodityInfoDTO();
            updateDto.setId(infoDTO.getId());
            String newLogUrls = Joiner.on(",").join(asList);
            log.info("新的logUrls:{}", newLogUrls);
            updateDto.setLogoUrls(newLogUrls);
            this.updateById(updateDto);
            /*//es修改
            CommodityEsVO commodityEsVO = this.queryESGoodsById(infoDTO.getId());
            List<EsGoodsDTO> esGoods = getEsGoods(commodityEsVO);
            for (EsGoodsDTO esGood : esGoods) {
                elasticsearchService.saveOrUpdateEntity(esGood,"index_goods_2020","goods",String.valueOf(infoDTO.getId()));

            }*/
        }
    }

    @Override
    public List<GoodsExportVO> getExportSku(String ids) {
        List<GoodsExportVO> result = new ArrayList<>();
        try {
            String[] idArray = ids.split(",");
            for (String id : idArray) {
                // 查询规格
                List<GoodsExportVO> sku = baseMapper.getSku(Long.valueOf(id));
                if (CustomizeUtil.listIsNotNull(sku)) {
                    for (GoodsExportVO goodsExportVO : sku) {
                        goodsExportVO.setPrice(goodsExportVO.getPrice().setScale(2, BigDecimal.ROUND_UP));
                        result.add(goodsExportVO);
                    }
                }
                // 查询套餐
                List<GoodsExportVO> skuA = baseMapper.getSkuA(Long.valueOf(id));
                if (CustomizeUtil.listIsNotNull(skuA)) {
                    for (GoodsExportVO exportVO : skuA) {
                        exportVO.setPrice(exportVO.getPrice().setScale(2, BigDecimal.ROUND_UP));
                        result.add(exportVO);
                    }
                }
            }
            return result;
        } catch (Exception e) {
            BigDecimal price = new BigDecimal("0.00");
            log.error("卖家端商品导出错误信息:{}", e.getMessage());
            GoodsExportVO goodsExportVO = new GoodsExportVO();
            goodsExportVO.setPrice(price.setScale(2, BigDecimal.ROUND_UP));
            result.add(goodsExportVO);
            e.printStackTrace();
        }
        return result;
    }

    @Override
    public Result<?> commodityOnAndOffShelves(Long id) {
        CommodityInfoDTO dto = this.selectById(id);
        if (dto == null) {
            return new Result<>(CodeEnum.FAIL_COMMODITY_ERROR_340000);
        }
        //判断店铺是否冻结
        boolean checkShopIsClose = shopInfoService.checkShopIsClose(dto.getShopId());
        if (!checkShopIsClose) {
            return new Result<>(CodeEnum.FAIL_COMMODITY_ERROR_340015);
        }
        //审核未通过的商品不能上下架
        if (dto.getAuditStatus() != 1) {
            return new Result<>(CodeEnum.FAIL_COMMODITY_ERROR_340001);
        }
        if (dto.getIsPublish().equals(0)) {
            return this.merchandiseOnTheShelf(dto);
        } else {
            return this.commodityOffTheShelf(dto);
        }
    }

    @Override
    public List<CommodityExportNewVO> queryExportList(CommodityAdminListBO bo) {
        return this.baseMapper.queryExportList(bo);
    }

    /**
     * 根据店铺id 下架所有商品
     * @param shopId
     * @return
     */
    @Override
    public Result updateNotPublishByShopId(Long shopId, String notes) {

        Integer num = this.baseMapper.updateNoPublishByShopIdAdmin(shopId, notes);
        if(num != null && num > 0){
            List<Long> ids = this.baseMapper.queryListByShopId(shopId);
            if(ids != null){
                for(Long id : ids){
                    searchService.deleteData("index_goods_2020", "goods", id.toString());
                }
            }
        }

        return new Result();
    }

    @Override
    public Integer allProducts() {
        Wrapper<CommodityInfoDTO> wrapper = new EntityWrapper<>();
        wrapper.eq("audit_status", 1);
        wrapper.eq("status", 0);
        List<CommodityInfoDTO> commodityInfoDTOS = this.selectList(wrapper);
        if (commodityInfoDTOS!=null && commodityInfoDTOS.size()>0){
            List<CommodityInfoDTO> commodityInfoDTO1 = new ArrayList<>();
            for (CommodityInfoDTO commodityInfoDTO : commodityInfoDTOS) {
                boolean b = shopInfoService.checkShopIsClose(commodityInfoDTO.getShopId());
                if (b){
                    commodityInfoDTO1.add(commodityInfoDTO);
                }
            }
            if (commodityInfoDTO1!=null && commodityInfoDTO1.size()>0){
                return commodityInfoDTO1.size();
            }
        }
        return 0;
    }

    @Override
    public Integer getPublishCount(Integer publishStatus) {
        return this.baseMapper.getPublishCount(publishStatus);
    }

    /**
     * @return : com.ztgf.common.constant.Result<?>
     * @Author :chenyu.wang
     * @Description : 商品上架
     * @Date : 2021.03.30 14:43
     * @Param : [dto]
     **/
    private Result<?> merchandiseOnTheShelf(CommodityInfoDTO dto) {
        //判断是否由平台下架，平台下架之后不能上架
        if (dto.getIsPlatformShelf().equals(1)) {
            return new Result<>(CodeEnum.FAIL_COMMODITY_ERROR_340002);
        }
        // 判断是否资质过期
        boolean expireStatus = shopQualificationService.getExpireStatus(dto.getShopId(), dto.getBrandId());
        if (!expireStatus) {
            return new Result<>(CodeEnum.FAIL_COMMODITY_ERROR_340013);
        }
        // 判断店铺是否变更且商品品牌类目不一致
        boolean checkShopCategoryBrand = this.checkShopCategoryBrand(dto);
        if (!checkShopCategoryBrand) {
            return new Result<>(CodeEnum.FAIL_COMMODITY_ERROR_340017);
        }
        CommodityInfoDTO updateDto = new CommodityInfoDTO();
        updateDto.setId(dto.getId());
        updateDto.setIsPublish(1);//上架
        boolean update = this.updateById(updateDto);
        if (!update) {
            return new Result<>(CodeEnum.FAIL_COMMODITY_ERROR_340003);
        }
        List<Long> ids = new ArrayList<>();
        ids.add(dto.getId());
        //判断商品是否掌柜推荐 0否、1是
        if (dto.getIsRecommend().equals(1)) {
            iEpgShopSectionService.addShopSectionBySectionType(ids, dto.getShopId(), ShoppingCodeEnum.SHOPPER_RECOMMEND_3.getMsg());
        }
        // 是否新品上架 0否、1是
        if (dto.getIsNew().equals(1)) {
            iEpgShopSectionService.addShopSectionBySectionType(ids, dto.getShopId(), ShoppingCodeEnum.NEW_SHOP_1.getMsg());
        }
        // 是否镇店之宝 0否、1是
        if (dto.getIsTreasure().equals(1)) {
            iEpgShopSectionService.addShopSectionBySectionType(ids, dto.getShopId(), ShoppingCodeEnum.SHOP_BABY_2.getMsg());
        }
        // 将商品添加进ES
        CommodityEsVO goods = baseMapper.queryESGoodsById(dto.getId());
        List<EsGoodsDTO> esGoods = this.getEsGoods(goods);
        searchService.addGoods("index_goods_2020", "goods", 0, esGoods.size(), esGoods);
        return new Result<>(CodeEnum.SUCCESS);
    }

    /**
     * @return : com.ztgf.common.constant.Result<?>
     * @Author :chenyu.wang
     * @Description : 商品下架
     * @Date : 2021.03.30 14:43
     * @Param : [dto]
     **/
    private Result<?> commodityOffTheShelf(CommodityInfoDTO dto) {
        CommodityInfoDTO updateDto = new CommodityInfoDTO();
        updateDto.setId(dto.getId());
        updateDto.setIsPublish(0);//下架
        boolean update = this.updateById(updateDto);
        if (!update) {
            return new Result<>(CodeEnum.FAIL_COMMODITY_ERROR_340004);
        }
        List<Long> ids = new ArrayList<>();
        ids.add(dto.getId());
        //判断商品是否掌柜推荐 0否、1是
        if (dto.getIsRecommend().equals(1)) {
            iEpgShopSectionService.deleteShopSectionBySectionType(ids, dto.getShopId(), ShoppingCodeEnum.SHOPPER_RECOMMEND_3.getMsg());
        }
        // 是否新品上架 0否、1是
        if (dto.getIsNew().equals(1)) {
            iEpgShopSectionService.deleteShopSectionBySectionType(ids, dto.getShopId(), ShoppingCodeEnum.NEW_SHOP_1.getMsg());
        }
        // 是否镇店之宝 0否、1是
        if (dto.getIsTreasure().equals(1)) {
            iEpgShopSectionService.deleteShopSectionBySectionType(ids, dto.getShopId(), ShoppingCodeEnum.SHOP_BABY_2.getMsg());
        }
        //从es中删除商品
        searchService.deleteData("index_goods_2020", "goods", dto.getId().toString());
        return new Result<>(CodeEnum.SUCCESS);
    }

    /**
     * @return : boolean
     * @Author :chenyu.wang
     * @Description : 检查店铺类目品牌
     * @Date : 2021.03.30 14:52
     * @Param : []
     **/
    private boolean checkShopCategoryBrand(CommodityInfoDTO dto) {
        Wrapper<ShopCategoryRelationDTO> wrapper = new EntityWrapper<>();
        wrapper.eq("shop_id", dto.getShopId());
        wrapper.eq("is_delete", 0);
        List<ShopCategoryRelationDTO> list = shopCategoryRelationService.selectList(wrapper);
        if (CustomizeUtil.listIsNull(list)) {
            return false;
        }
        for (ShopCategoryRelationDTO shopCategoryRelationDTO : list) {
            if (dto.getBrandId().equals(shopCategoryRelationDTO.getBrandId()) && dto.getCategoryId().equals(shopCategoryRelationDTO.getCategoryId())) {
                return true;
            }
        }
        return false;
    }

}
